I am new to Rails. I am trying to duplicate a user from @users model, based on a match and then add it back in as a new row within the @users model. I am doing this as a quick one-off situation and doing it in the users_controller.rb
I have the following pseudocode --
@users = users.includes(:products).order('orders.created_at DESC')
@new_user = @user.where(slug: "john-doe").first
if !@new_user.nil?
@new_user = @user.where(slug: "john-doe").first.clone
@user << @new_user
end
However, within the view of the associated controller when I do the following --
<%= @new_user.inspect %>
It shows but when I do
<%= @users.inspect %>
It doesn't show @new_user actually added. Appreciate the help!
Cloning an object in ActiveRecord will create a new instance but will tie it to the same db record. ActiveRecord keeps state indicating it's relation to the db (like the primary key field (id) for example)
One way to create a clone is to copy the attributes you want over to the new instance:
a = @user.where(slug: "john-doe").first.attributes
a.delete('id')
User.create(a)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.