1

MichaelHartlRailsチュートリアルを終了しました。自分で何かを作ろうとしています。

作成しようとしている関係をレールに理解させるのに問題があります。これをできるだけ単純化するようにします。枝、小枝、葉のある木は適切ですが...

例として親子フォーマットを使用します。だから当然私にはユーザーがいて、ユーザーが家族を作ったとしましょう。

それで:

Class User < ActiveRecord::Base

 has_many :families
 has_many :parents
 has_many :children

end

Class Family < ActiveRecord::Base

 belongs_to :user
 has_many :parents

end

Class Parent < ActiveRecord::Base

 belongs_to: :user
 belongs_to: :family
 has_many: :children

end

Class Child < ActiveRecord::Base

 belongs_to :user
 belongs_to :parent

end

ご覧のように、私は子供が家族に属する親に属していることを望んでいますが、子供自体は親を介さない限り家族に属していません。これが比喩ではなかった場合は悲しいですが、この特定のケースでは真実です。;)

私は親の下で試しました:

has_many :children, through: :parent

has_many :children, through: :family

しかし、それはうまくいきませんでした。

私が使おうとすると:

User.family.new

また

User.child.new 

...メソッドが存在しないと表示されます。私はそれが関係を理解し​​ていないことを意味すると解釈します。

私は何が間違っているのですか?

関連する場合、現時点では、ファミリ、親、子のテーブルで唯一のものは次の列です。

  t.string :content
  t.integer :user_id
4

1 に答える 1

2

これらのメソッドはありません。

User.family.new
User.child.new

関連付けを定義するときは、has_many関連付けられた新しいオブジェクトを作成するための次のメソッドがあります。

collection.build(attributes = {}, …)
collection.create(attributes = {})

Railsガイドに従ってください:

コレクションは、has_manyの最初の引数として渡されたシンボルに置き換えられます

詳細については、このhas_manyアソシエーションリファレンスを参照してください。したがって、User新しい家族または子を作成する場合は、次の方法を使用する必要があります。

user = User.create(name: "ABC") # create new user and save to database. 
user.families.build  # create new family belongs to user
user.children.build  # create new children belongs to user

user.families.create # create new family belongs to user and save it to database.
user.children.create # create new child belongs to user and save it to database.

子を家族に属する親に所属させたい場合は、関連付けを変更できます。

Class Family < ActiveRecord::Base

 belongs_to :user
 has_many :parents
 has_many :children, through: :parents # Get children through parents
end

Class Parent < ActiveRecord::Base

 belongs_to: :user
 belongs_to: :family
 has_many: :children

end

Class Child < ActiveRecord::Base

 belongs_to :user
 belongs_to :parent

end

これで、すべての子を家族に属する親に属するようにすることができます(私は家族がid = 1であると仮定します)。

 f = Family.find(1) # Find a family with id = 1
 f.children # Get all children in family.
于 2012-11-29T05:33:13.840 に答える