10

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

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 的最佳位置,以便在存在同名的乐队时可以使用现有乐队?

4

1 回答 1

19

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

s1.bands.where(name: 'Wet Food').first_or_create
于 2013-10-19T23:35:18.813 回答