find_or_create on a有很多关系

wir*_*din 9 ruby-on-rails has-many-through ruby-on-rails-3

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

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

乐队的独特之处在于:名字

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
Run Code Online (Sandbox Code Playgroud)

新乐队的创建方式如下:

(假设我们已经保存了一个名为s1的节目记录)

> s1.bands.new(name: "Wet Food")
> s1.save
Run Code Online (Sandbox Code Playgroud)

现在,只有当一个名为"湿食"的乐队尚不存在时,这才会保存

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

Jer*_*een 16

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

s1.bands.where(name: 'Wet Food').first_or_create
Run Code Online (Sandbox Code Playgroud)