【发布时间】:2013-10-28 10:31:58
【问题描述】:
我的应用中有很多直通关系:
Shows有很多乐队到=> 阵容
乐队是唯一的:name
class Show < ActiveRecord::Base
attr_accessible :city_id, :title, :dateonly, :timeonly, :image, :canceled, :venue_attributes, :bands_attributes
belongs_to :city
belongs_to :venue
has_many :lineups
has_many :bands, through: :lineups
has_and_belongs_to_many :users
end
class Lineup < ActiveRecord::Base
belongs_to :show
belongs_to :band
end
class Band < ActiveRecord::Base
attr_accessible :name, :website, :country, :state
has_many :lineups
has_many :shows, through: :lineups
validates :name, presence: true
validates_uniqueness_of :name
before_save :titleize_name
private
def titleize_name
self.name = self.name.titleize
end
end
新乐队是这样创建的:
(假设我们已经保存了一个名为 s1 的节目记录)
> s1.bands.new(name: "Wet Food")
> s1.save
目前,只有在名为“Wet Food”的乐队尚不存在时才会保存
在这种关系中,在哪个模型中进行 Band.find_or_create 的最佳位置,以便在存在同名的乐队时可以使用现有乐队?
【问题讨论】:
-
使用 Band.find_or_create 将在哪里使用现有乐队?并尝试使用 Band.where(name: 'Wet Food').first_or_create 而不是 Band.find_or_create。
-
阵容包含band_id,所以我猜是吗?
-
所以阵容类似于表演,一个乐队每场表演一个。一个节目有多个表演。
-
是的,我将它重命名为,它更有意义。谢谢!
-
如果您想使用,请使用:s1.bands.where(name: 'Wet Food').first_or_create。
标签: ruby-on-rails ruby-on-rails-3 has-many-through