find_or_create on a有很多关系

我的应用程序中有很多关系:

节目有很多乐队通过=> 阵容

乐队是独一无二的:名字

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 

现在只有在一个名为“湿食”的乐队尚不存在的情况下才能保存

在这种关系中哪个模型是Band.find_or_create的最佳位置,以便在存在同名的情况下可以使用现有的band?

这通常是Controller (或可能是服务对象)中的调用类型,但不在Model 。 这实际上取决于您尝试在应用中完成的特定用户流程。 基本上,无论你在哪里使用s1.bands.new ,你都可以使用它:

 s1.bands.where(name: 'Wet Food').first_or_create