[英]How do I save a matched record as a new one and update user_id, using rails and postgresql
I am matching incomplete and complete records using postgresql in rails. 我在rails中使用postgresql匹配不完整和完整的记录。 Here's the matching code:
这是匹配的代码:
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
I want to save a duplicate of the matched record with the current_user's user_id. 我想使用current_user的user_id保存匹配记录的重复项。 I'm currently using a convoluted work-around where I set a variable, ie, abc = match, and then parse the match, ie, user_id = abc.user_id, so that I can create a new QualifyingEvent with the params, eg, :class_date, :course_id, :sponsor_name, and :user_id
我当前正在使用一种复杂的解决方法,在该方法中,我设置了一个变量(即abc = match),然后解析了该匹配(即user_id = abc.user_id),以便可以使用参数创建新的QualifyingEvent,例如, :class_date,:course_id,:sponsor_name和:user_id
I tried abc = QualifyingEvent.new and then abc = match and abc.save. 我尝试了abc = QualifyingEvent.new,然后尝试abc = match和abc.save。 It didn't work.
没用
There must be an easier way?! 一定有更简单的方法吗? Thank you in advance for your help.
预先感谢您的帮助。
I tried abc = QualifyingEvent.new and then abc = match and abc.save.
我尝试了abc = QualifyingEvent.new,然后尝试abc = match和abc.save。 It didn't work.
没用
That would make one object equal to another object whereas what you are really wanting to do is just assign the attributes of one object to another object 那会使一个对象等于另一个对象,而您真正想要做的就是将一个对象的属性分配给另一个对象
abc = QualifyingEvent.new
abc.assign_attributes(match.attributes)
Then sort out the current_user id to whatever value you want plus set the date/time stamps for created_at, updated_a and the id to nil as Rails and the RDBMS will take care of those values when record is saved. 然后将current_user id排序为所需的任何值,然后将created_at,updated_a的日期/时间戳记设置为nil并将其设置为nil,作为Rails,并且在保存记录时RDBMS将处理这些值。
Also to get around the mass assignment protection you can use the :without_protection => true argument 也可以使用:without_protection => true参数来绕过批量分配保护
abc.assign_attributes(match.attributes, :without_protection => true)
see the docs for more info http://apidock.com/rails/ActiveRecord/Base/assign_attributes 有关更多信息,请参阅文档http://apidock.com/rails/ActiveRecord/Base/assign_attributes
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.