find_or_create on a has many through relationship

孤街醉人 提交于 2020-01-24 02:26:11

问题


I have a has many through relationship in my app:

Shows has many Bands through => Lineups

Bands are unique by :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

New Bands are created like this:

(lets say we have a show record already saved called s1)

> s1.bands.new(name: "Wet Food")
> s1.save

Right now this will only save if a band named "Wet Food" doesn't already exist

In which model is the best place to do a Band.find_or_create in this relationship so that an existing band can be used if one with the same name exists?


回答1:


This is generally the type of call that would go in a Controller (or maybe a service object), but not in a Model. It really depends on the particular user flow that you're trying to accomplish in your app. Basically, where ever you are already using s1.bands.new, you could use this instead :

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


来源:https://stackoverflow.com/questions/19469002/find-or-create-on-a-has-many-through-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!