Reputation: 2228
I'm trying to use a model as a template to create a new model. However, I only want to use the attr_accessible
attributes from the template model.
Here's what I'm doing now. It works, but it seems too complex.
def copy_attrs_and_errors(other)
self.class.attr_accessible[:default].to_a.each do |attr|
eval("self.#{attr} = other.#{attr}") unless attr.blank?
end
end
I'd like to be able to say something as simple as:
self.attributes = other.whitelist_attributes(:default)
Thanks.
Upvotes: 0
Views: 531
Reputation: 18845
it's a little crazy, but you could do something like this in a module or whatever:
def self.from_accessible_attributes(other)
values = other.attributes.values_at(*other.class.accessible_attributes)
attributes = Hash[other.class.accessible_attributes.zip(values)]
new(attributes)
end
Upvotes: 1