2017-08-20 7 views
0

私は2つのモデル "グループ"と "動き"を持つシナリオを持っています。 グループには多数の動作があり、すべての動作はグループに関連しています。 動きは、グループが1つである可能性があるさまざまなモデルの1つに関連する場合もあります。多形1つのモデルとの二重の関係

したがって、グループ&と、モーション&グループとの間の多相関係の間にhas_many関係があります。

class Group < ApplicationRecord 
    has_many :motions 
    has_many :motions, as: :motionable 
end 

class Motion < ApplicationRecord 
    belongs_to :group 
    belongs_to :motionable, polymorphic: true 
end 

これは動きで新しいレコードを動作するように見える一方で、私はhas_manyの関係を必要とするのに対し、多型の関係を作成します。

2.4.1 :010 > Group.first.motions.new 
    Group Load (1.5ms) SELECT "groups".* FROM "groups" ORDER BY "groups"."id" ASC LIMIT $1 [["LIMIT", 1]] 
=> #<Motion id: nil, group_id: nil, motionable_type: "Group", motionable_id: 1> 

答えて

0

私はこの次を使用して、今取り組んでいる:

class Group < ApplicationRecord 
    has_many :motions 
    has_many :subjects, class_name: "Motion", as: :motionable 
end 

class Motion < ApplicationRecord 
    belongs_to :group 
    belongs_to :motionable, polymorphic: true 
end 

私はこれを次から選んだ: http://guides.rubyonrails.org/association_basics.html#self-joins

私が今使ってhas_manyの関係を作成することができます

Group.first.motions.new 

および多型の関係使用:

Group.first.subjects.new 
関連する問題