How to clone a model's attributes easily?

Posted by Zabba on Stack Overflow See other posts from Stack Overflow or by Zabba
Published on 2011-01-13T00:49:08Z Indexed on 2011/01/13 0:53 UTC
Read the original article Hit count: 165

Filed under:
|
|

I have these models:

class Address < ActiveRecord::Base
  belongs_to :event
  attr_accessible :street, :city
  validates :street, :city, :presence => true 
end

class Event < ActiveRecord::Base
  has_one :address
  accepts_nested_attributes_for :address
end

If I do the below assignment in the Events create action and save the event I get an error:

#Use the current user's address for the event
@event.address_attributes = current_user.address.attributes

#Error occurs at the above mentioned line
ActiveRecord::RecordNotFound (Couldn't find Address with ID=1 for Event with ID=)

I think what's happening is that all the address's attributes (including the primary key) is getting assigned in the @event.address_attributes = line.

But all I really want is the "real data" (street, city), not the primary keys or created_at etc to get copied over.

I suppose I could write a small method to do this sort of selective copy but I can't help but feel there must be some built-in method for this?

What's the best/right way to do this?

© Stack Overflow or respective owner

Related posts about attributes

Related posts about model