ruby on rails - Dual relationship to model with one polymorphic -
i have scenario have 2 models "group" , "motion". group may have many motions , every motion related group. motion may related 1 of various models of group may one.
so have has_many relationship between group & motion , polymorphic relationship between motion & group.
class group < applicationrecord has_many :motions has_many :motions, as: :motionable end class motion < applicationrecord belongs_to :group belongs_to :motionable, polymorphic: true end
whilst appears work new record in motions creates polymorphic relationship whereas require has_many relationship:
2.4.1 :010 > group.first.motions.new group load (1.5ms) select "groups".* "groups" order "groups"."id" asc limit $1 [["limit", 1]] => #<motion id: nil, group_id: nil, motionable_type: "group", motionable_id: 1>
i have working using following:
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
i picked following: http://guides.rubyonrails.org/association_basics.html#self-joins
i can create has_many relationship using:
group.first.motions.new
and polymorphic relationship using:
group.first.subjects.new
Comments
Post a Comment