如何使用 rails 和 postgresql 将匹配记录保存为新记录并更新 user_id

How do I save a matched record as a new one and update user_id, using rails and postgresql

我在 rails 中使用 postgresql 匹配不完整和完整的记录。这是匹配代码:

QualifyingEvent.where("(class_date = :class_date AND course_id = :course_id) 
                    OR (class_date = :class_date AND sponsor_name = :sponsor_name) 
                    OR (course_id = :course_id AND sponsor_name = :sponsor_name)",
                      class_date: '2001-01-01',
                      course_id: 'A111',
                      sponsor_name: 'ICPAS').first

我想保存与 current_user 的 user_id 匹配记录的副本。我目前正在使用一个复杂的解决方法,我设置一个变量,即 abc = match,然后解析匹配,即 user_id = abc.user_id,这样我就可以创建一个新的 QualifyingEvent使用参数,例如:class_date、:course_id、:sponsor_name 和:user_id

我尝试了 abc = QualifyingEvent.new,然后是 abc = match 和 abc.save。没用。

一定有更简单的方法吧?!预先感谢您的帮助。

I tried abc = QualifyingEvent.new and then abc = match and abc.save. It didn't work.

这会使一个对象等于另一个对象,而您真正想要做的只是将一个对象的属性分配给另一个对象

abc = QualifyingEvent.new
abc.assign_attributes(match.attributes)

然后将 current_user id 整理成你想要的任何值加上 created_at、updated_a 的 date/time 标记和 [=27] 的 nil =] 并且 RDBMS 将在保存记录时处理这些值。

还可以使用 :without_protection => true 参数来绕过批量赋值保护

abc.assign_attributes(match.attributes, :without_protection => true)

查看文档了解更多信息http://apidock.com/rails/ActiveRecord/Base/assign_attributes