简体   繁体   English

Rails试图将记录添加到变量

[英]Rails Trying to Add a Record to Variable

I am new to Rails. 我是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. 我试图根据匹配从@users模型复制一个用户,然后将其添加回@users模型内的新行中。 I am doing this as a quick one-off situation and doing it in the users_controller.rb 我正在将这种情况作为一种一次性的情况,并在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. 它没有显示实际添加的@new_user。 Appreciate the help! 感谢帮助!

Cloning an object in ActiveRecord will create a new instance but will tie it to the same db record. 在ActiveRecord中克隆对象将创建一个新实例,但会将其绑定到同一数据库记录。 ActiveRecord keeps state indicating it's relation to the db (like the primary key field (id) for example) ActiveRecord保持状态以指示其与数据库的关系(例如,主键字段(id))

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM