我有这些模型
class EventGroups < ActiveRecord::Base
has_many :festival_venues
has_many :venues, :through => :festival_venues
end
class Venue < ActiveRecord::Base
has_many :festival_venues
has_many :event_groups, :through => :festival_venues
end
class FestivalVenue < ActiveRecord::Base
belongs_to :event_group
belongs_to :venue
end
我该怎么做?
答案 0 :(得分:3)
class EventGroup < ActiveRecord::Base
has_many :festival_venues, dependent: :destroy
has_many :venues, :through => :festival_venues, :dependent => :destroy
end
class Venue < ActiveRecord::Base
has_many :festival_venues
has_many :event_groups, :through => :festival_venues
end
class FestivalVenue < ActiveRecord::Base
belongs_to :event_group
belongs_to :venue
end
现在,如果您将event_group
变量绑定到EventGroup
个对象,则可以使用以下代码创建Venue
(及其FestivalVenue
):
venue = Venue.create(your_attributes)
event_group.venues << venue
答案 1 :(得分:1)
在下面的代码中,Model类名必须是单数。将班级名称EventGroups
更改为EventGroup
。现在它将像魅力一样发挥作用。
class EventGroup < ActiveRecord::Base
has_many :festival_venues, dependent: :destroy
has_many :venues, :through => :festival_venues, :dependent => :destroy
end
剩下的代码很好。
class Venue < ActiveRecord::Base
has_many :festival_venues
has_many :event_groups, :through => :festival_venues
end
class FestivalVenue < ActiveRecord::Base
belongs_to :event_group
belongs_to :venue
end
希望它会有所帮助。感谢