说我有两个班,使用ActiveRecord执行此操作的正确方法?
形象和信用
class Image < ActiveRecord::Base
belongs_to :credit
accepts_nested_attributes_for :credit
end
class Credit < ActiveRecord::Base
#has a field called name
has_many :images
end
我希望有一个信贷创建图像时,关联作用有点像一个标签。从本质上讲,我希望像Credit.find_or_create_by_name这样的行为,但是在使用Credit的客户端代码中,如果它只是一个Create,它会更清洁。我似乎无法找到一种方法将其烘焙到模型中。当你创建一个图像,你可以做什么
class Image < ActiveRecord::Base
belongs_to :credit
attr_accessor :credit_name
after_create { Credit.associate_object(self) }
end
class Credit < ActiveRecord::Base
#has a field called name
has_many :images
def self.associate_object(object, association='images')
credit = self.find_or_create_by_name(object.credit_name)
credit.send(association) << object
credit.save
end
末
然后是像
Image.create(:attr1 => 'value1', :attr2 => 'value2', ..., :credit_name => 'some_name')
,它会带你送入名称:
“信用”就像电影上的信用(归属),而不是账户上的信用(付款),对吗? – jefflunt 2012-02-02 19:20:47
是的,对不起。在新闻编辑室工作2.5年,扭曲了我的行话。 – 2012-02-02 19:22:57