0

我有这些模型

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. 当我删除VenueFestivalVenue中的Eventgroups相关记录时,也应该删除。

我怎样才能做到这一点?

4

2 回答 2

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
于 2013-08-01T18:41:07.560 回答
1

在您的以下代码中,模型类名称必须是单数。将类名更改EventGroupsEventGroup. 现在它会像一个魅力一样工作。

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

希望它会有所帮助。谢谢

于 2013-08-01T19:21:29.763 回答