Rails更新单个属性不起作用

时间:2014-03-21 12:20:56

标签: ruby-on-rails ruby

我有以下情况:

用户取消其帐户,并可选择提供原因。 保存原因,并且用户是soft_deleted。

出于某种原因,我设置原因的代码不会导致保存任何更新。

这是我的代码:

class User < ActiveRecord::Base

    def set_cancellation_reason(reason)
        cancellation_reason = reason
        save!
    end

end

这里有什么错误,cancel_reason没有被持久化?

如果我从控制台运行代码会发生这种情况:

 u = User.first
  User Load (2.0ms)  SELECT "users".* FROM "users" WHERE "users"."deleted_at" IS NULL ORDER BY "users"."id" ASC LIMIT 1
 => #<User id: 1, email: "leebrooks0@gmail.com", encrypted_password: "$2a$15$GQ.WHk.nxlArc668bf3NW.WFJVV.ost3R85PGs6ePYaT...", role_id: nil, reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 11, current_sign_in_at: "2014-03-21 12:08:54", last_sign_in_at: "2014-03-21 12:06:31", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", confirmation_token: nil, confirmed_at: "2014-03-21 10:59:27", confirmation_sent_at: nil, unconfirmed_email: nil, failed_attempts: 0, unlock_token: nil, locked_at: nil, cancellation_reason: nil, created_at: "2014-03-21 10:59:27", updated_at: "2014-03-21 12:12:29", deleted_at: nil> 
2.1.1 :008 > u.set_cancellation_reason("hogwash")
   (0.5ms)  BEGIN
   (0.4ms)  COMMIT
 => true 

2 个答案:

答案 0 :(得分:2)

我可能会错过关于如何调用它的内容,但我会做以下事情。我假设这是从控制器或视图调用的。

Called by using myuser.set_cancellation_reason("don't like it")

def set_cancellation_reason(reason)
    self.cancellation_reason = reason
    self.save!
end

我还假设你设置了取消的标志,除了你需要的其他东西之外

self.cancel_flag = true

答案 1 :(得分:2)

执行cancellation_reason = reason时,它会创建一个cancellation_reason变量,而不是调用Active Record定义的动态方法cancellation_reason=

self是默认接收器,但是当表达式可能被模糊地视为分配时,分配将获胜。

您可以使用self.cancellation_reason = reason确保选择rails方法,但我更喜欢执行以下操作:

update_attribute(:cancellation_reason, reason)

我认为它更清楚,你不需要额外的一行来保存。