4

これは簡単な質問のように思えますが、私にはちょっとしたパズルです:

class Parent
  has_many children
  ...
end

class Child
  belongs_to parent
end

p = Parent.find(111)
c = Child.all.where(parent: p)

なぜそれがうまくいかないのか、なぜ私はしなければならないのか:

c = Child.all.where(parent_id: p.id)

補遺

より複雑なケースでは、より複雑なロジックに基づいて関係を作成する必要があります。

c = Child.where(age: 32, city: "boston")
c.where(parent: p) # wouldn't work

補遺#2

これを説明するには、多対多にする必要があります。

class Teacher
   has_many :students, through: ClassRoom
   has_many :classes
end

class ClassRoom
  belongs_to :teacher
  belongs_to :child
end

class Child 
  has_many :classes
  has_many :teachers, through: ClassRoom
end
t = Teacher.first
c = Child.where(age: 5, city: "boston")

c.where(teacher: t) # wouldn't work
c.where(teacher_id: t.id) # would work but is a little ugly

補遺3

素晴らしい情報をありがとう!上記の例の最後の行を実行するためのより良い (または「正しい」) 方法はありますか?

c.where(teacher_id: t.id) # would work but is a little ugly
4

3 に答える 3

2

「アクティブレコードオブジェクトは属性を直接指定するのではなく、リンクされているテーブル定義から推測します」 - http://api.rubyonrails.org/files/activerecord/README_rdoc.html

この関連付けは特定のデータベース列によってリンクされているため、それらの属性を使用して関係を参照する必要があります。

p.children親の子の配列を返す which を使用して、このステートメントを簡略化することもできます。

于 2013-04-26T20:16:25.377 に答える