我在 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 和 id 的日期/时间戳设置为 nil,因为 Rails 和 RDBMS 将在保存记录时处理这些值。
还可以使用 :without_protection => true 参数来绕过批量赋值保护
abc.assign_attributes(match.attributes, :without_protection => true)
有关更多信息,请参阅文档 http://apidock.com/rails/ActiveRecord/Base/assign_attributes
关于ruby-on-rails - 如何使用 rails 和 postgresql 将匹配记录保存为新记录并更新 user_id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27782966/