Here is my weird problem. Two models like following:
Lexeme id:int name:string
Structure id:int ref_id:string meta_id:int
Lexeme can have many structure records through foreign key 'ref_id' in the structures table. And these structure records belonging to one lexeme differs between each other using meta_id. And if Lexeme has structures, then there must be a top_struct whose structure.id is 0. This is the association I specified.
class Lexeme
has_one :top_struct, :class=>'Structure', :foreign_key=>'ref_id', :conditions=>'structures.meta_id=0' has_many: all_structs, :class=>'Structure', :foreign_key=>'ref_id' end
class Structure belongs_to :lexeme, :class=>'Lexeme', :foreign_key=>'ref_id' end
After these definition, say I want to find 'those lexemes that have structures when structures.id <10'. I tried the following two find
Lexeme.find (:all, :include=>:top_struct, :conditions=>'structures.id<10') Lexeme.find (:all, :include=>:all_structs, :conditions=>'structures.id<10')
Then finds gives out same error For the first one ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'lexemes.ref_id' in 'field list': SELECT `lexemes`.`id` AS t0_r0, `lexemes`.`name` AS t0_r1, `lexemes`.`ref_id` AS t0_r2, `lexemes`.`meta_id` AS t0_r3, `structures`.`id` AS t1_r0, `structures`.`ref_id` AS t1_r1, `structures`.`meta_id` AS t1_r2, FROM `lexemes` LEFT OUTER JOIN `structures` ON structures.ref_id = lexemes.id and structures.meta_id=0 WHERE (structures.id<10)
For the second one ActiveRecord::StatementInvalid: Mysql::Error: Unknown column 'lexemes.ref_id' in 'field list': SELECT `lexemes`.`id` AS t0_r0, `lexemes`.`name` AS t0_r1, `lexemes`.`ref_id` AS t0_r2, `lexemes`.`meta_id` AS t0_r3, `structures`.`id` AS t1_r0, `structures`.`ref_id` AS t1_r1, `structures`.`meta_id` AS t1_r2, FROM `lexemes` LEFT OUTER JOIN `structures` ON structures.ref_id = lexemes.id WHERE (structures.id<10)
Apparently, my 'lexemes' table dose not have 'ref_id' and 'meta_id' field. And I'm using rails 2.2.2
But when I change the 'conditions' field to conditions on lexemes table, everything goes fine. Lexeme.find(:all, :include=>:top_struct, :conditions=>'lexemes.id<10') Lexeme.find (:all, :include=>:all_structs, :conditions=>'lexemes.id<10')
Can anyboby please explain to me why this is happening?