尝试更新消息模型中的值read_at时,使用update_attributes函数没有任何效果。rails update_attributes不更新值
这里是消息表
class CreateMessages < ActiveRecord::Migration
def change
create_table :messages do |t|
t.integer :sender_id, null: false
t.integer :receiver_id
t.string :subject
t.text :body
t.datetime :read_at
t.string :container, default: "draft"
t.boolean :sender_deleted, default: false
t.boolean :receiver_deleted, default: false
t.timestamps
end
end
def down
drop_table :messages
end
end
下面是消息模型
class Message < ActiveRecord::Base
attr_accessible :subject, :body, :container, :sender_id, :receiver_id, :read_at
belongs_to :sender,
class_name: 'User'
belongs_to :receiver,
class_name: 'User'
这里是用户模型
class User < ActiveRecord::Base
has_many :messages_sent,
class_name: 'Message',
foreign_key: 'sender_id',
dependent: :destroy
has_many :messages_received,
class_name: 'Message',
foreign_key: 'receiver_id',
dependent: :destroy
则在终端
user1 = User.create(name: "user1_name", email: "[email protected]", password: "foobar", password_confirmation: "foobar")
user2 = User.create(name: "user2_name", email: "[email protected]", password: "foobar", password_confirmation: "foobar")
msg1 = Message.create(sender_id: user1.id, receiver_id: user2.id, subject: 'subject_msg1', body: 'body_msg1')
msg1.save
@m = Message.find(msg1.id)
@m.update_attributes(read_at: Time.now)
我得到这样的输出:
@m.read_at
=>datestamped
msg1.read_at
=>nil
可以肯定我在这里失去了一些东西,但我不能看到它在哪里发生变化,rechanging的的has_many和belongs_to的从协会后,因为我确实把read_at通过attr_accessible列表 帮助!
尽管** @ m **和** msg1 **具有相同的** id **,所以使用'@ m.update_attributes(read_at:Time.now)'将更新** read_at * *仅来自** @ m **的属性。执行'msg1.reload'后,它将更新** msg1.read_at **值。我不明白为什么?在我的消息模型中,使用函数来更新attr,如果我不在自己的消息中使用** reload **,它就不起作用。你能解释为什么吗?我确实在其他attr上工作,只有在这个时候它才不会自我更新 – fejao