find_or_create上有很多直通关系 [英] find_or_create on a has many through relationship
问题描述
我的应用中有很多直通关系:
I have a has many through relationship in my app:
演出通过=> 阵容
频段按: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:
(假设我们已经保存了一个名为s1的放映记录)
(lets say we have a show record already saved called s1)
> s1.bands.new(name: "Wet Food")
> s1.save
现在,只有在不存在名为"Wet Food"的乐队时,此功能才会保存
Right now this will only save if a band named "Wet Food" doesn't already exist
在哪种模型中以这种关系进行Band.find_or_create的最佳位置,以便在存在相同名称的情况下可以使用现有的乐队?
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?
推荐答案
这通常是在Controller
(或者可能是服务对象)中进行的调用类型,而不是在Model
中进行的调用类型.这实际上取决于您要在应用程序中尝试完成的特定用户流.基本上,只要您已经在使用s1.bands.new
的地方,都可以使用它:
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
这篇关于find_or_create上有很多直通关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!