我的应用程序中有很多直通关系:
Shows通过 => Lineups有很多乐队
乐队是独一无二的 :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 的最佳位置,以便在存在同名的乐队时可以使用现有乐队?