开发者

Rails: save a record via belongs_to and setting the foreign key

Is there a better way of writing this code? It just doesn't sit right with me, I feel like there is something really 'rails开发者_C百科 like' that I should already know:

belongs_to :parent_in_use
belongs_to :parent_template

def after_create
  new_parent_in_use = ParentInUse.create!(self.parent_template.attributes)
  self.update_attribute(:parent_in_use_id, new_parent_in_use.id)
end

After creating a record I am taking the selected parent template and creating a parent_in_use record based on it. This way the template can change and the in_use record will live with my object forever. Both the ParentInUse and ParentTemplate classes inherit from Parent using STI.

I'm sure this should be simple enough but I don't know how to do it, basically I would like to create the and assign the record in one operation.


This will do what you're looking for.

def after_create 
  self.parent_in_use = ParentInUse.create!(parent_template.attributes)
end

However without other changes it won't do you any good. Because the foreign key is stored in the current model, ActiveRecord won't save the change if this association is created by an after_create call back. The new ParentInUse object will be saved, but the database row for the current model will not be updated with that corresponding parent_in_use_id.

Call it as a before_create call back and things will go more smoothly.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜