Chris B
Chris B

Reputation: 875

Duplicating an ActiveRecord in Rails, issues creating new object using existing paramters

I'm trying to duplicate a resource in Rails in my application and was running into some issues.

The setup is: I have a library of 'item templates' that the user can use, then modify the resulting item. I currently have a setup like this:

@temp_item = @template_item.dup
@new_item = @user.items.create(@temp_item.attributes)

However I'm running into a problem where it's trying to copy across protected attributes as well (namely created_at and updated_at). I'd rather not list out each attribute individually, so my question is, is there a way to exclude attributes being copied in this instance?

Thanks.

Upvotes: 3

Views: 604

Answers (3)

Mark Paine
Mark Paine

Reputation: 1894

Incorporating Mischa's good suggestion into my original answer.

@temp_item_attributes = @template_item.attributes.reject{ |k,v|
  %w(created_at updated_at).include?(k)
}
@new_item = @user.items.create(@temp_item_attributes)

Upvotes: 7

Patrick Klingemann
Patrick Klingemann

Reputation: 9014

seems to me you should do a combination of Mark Paine and Mischa's answers, namely:

temp_item_attributes = @template_item.attributes.reject do |k,v|
  %w(created_at updated_at).include?(k)
end
@new_item = @user.items.create(temp_item_attributes)

I can't believe there isn't a convenience method for this behavior; I didn't look too hard, but didn't find one.

Upvotes: 2

Mischa
Mischa

Reputation: 43298

I agree with Mark in using reject, but instead of using case/when, I'd do this:

@template_item.attributes.reject{ |k,v| %w(created_at updated_at).include?(k) }

Upvotes: 4

Related Questions