【问题标题】:Active record update attributes without attr_accessible没有 attr_accessible 的活动记录更新属性
【发布时间】:2014-08-25 01:32:47
【问题描述】:

我有一篇示范文章。创建完成后,我们会向用户发送一个带有令牌的激活码。 此激活码是故意列入黑名单的,因此不会添加到 attr_accesible 列表中。

一旦用户回来激活代码

articleitem = Article.find_by_activation_code(params[:code])
articleitem.activation_code = ""

现在我们如何更新记录。我不想使用保存,因为它会激活 before_save 方法

我已经在控制器中尝试了以下所有内容。

articleItem.update(activation_code: "")
update method is private

articleItem.update_attributes(activation_code: "")
WARNING: Can't mass-assign protected attributes: activation_code

更新记录的其他替代方法是什么

【问题讨论】:

  • 听起来像是您的 before_save 方法中的任何内容,如果您经常想保存而不调用它们,则可能不应该。
  • 不太明白你的问题。当您想要更新属性时,无论您遵循什么选项,最终都会保存它。将使用您使用的任何其他方法调用 Save。

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2


【解决方案1】:

另一种方法是设置一个虚拟属性(未经测试的代码)

in model

attr_accessor :execute_before_save
before_save :some_method

def some_method
  # Check is execute_before_save is set, if not let the method execute no matter what
  if execute_before_save || true
     # your code follows
  end
end

in your controller

articleitem = Article.find_by_activation_code(params[:code])
articleItem.execute_before_save = false
articleitem.activation_code = ""
articleitem.save

这样你可以控制你的before_save 回调,但它需要你设置虚拟属性,这是开销。

如果有帮助,请告诉我。

【讨论】:

  • 我通过使用 self.new_record 实现了这样的目标?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多