如何将记录添加到has_many:通过Ruby on rails上的关联

时间:2013-08-01 18:30:59

标签: ruby-on-rails ruby-on-rails-3 activerecord

我有这些模型

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
  1. 现在我想通过 Eventgroups 创建 Venue ,并且还应创建 FestivalVenue 中的记录。
  2. 当我删除 Venue 中的 Eventgroups 相关记录时 FestivalVenue 也应该删除。
  3. 我该怎么做?

2 个答案:

答案 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

希望它会有所帮助。感谢