0

When trying to update the value read_at from Message model it don't have any kind of effect using the update_attributes function.

Here is the Message table

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

Here is Message Model

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'

Here is User Model

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

Then at the terminal

user1 = User.create(name: "user1_name", email: "user1@email.com", password: "foobar", password_confirmation: "foobar")
user2 = User.create(name: "user2_name", email: "user2@email.com", 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)

I get this outputs:

@m.read_at
=>datestamped

msg1.read_at
=>nil

For sure I'm missing something here, but I can't see where it is after changing and rechanging the has_many and the belongs_to from the associations, because I did put the read_at over the attr_accessible list HELP!

4

3 回答 3

3

你应该msg1.reload先跑msg1.read_at

或者

msg1.reload.read_at
于 2013-07-26T04:58:58.600 回答
1

为了更新值,您应该使用

@m.update_attributes(:read_at => Time.now)

有关详细信息,请参阅文档

于 2013-07-26T04:04:11.037 回答
0

直接来自文档。

使用 attr_accessible 防止(由用户)大量分配不应由用户编辑的属性。质量分配用于标准控制器的创建和更新方法。

例如,对于普通用户帐户,您只希望用户可以编辑登录名和密码。应该不可能通过批量分配来更改状态属性。

class User < ActiveRecord::Base   
  attr_accessible :login, :password
end

因此,执行以下操作将愉快地返回 true,但不会更新 status 属性。

@user.update_attributes(:status => 'active')

如果要更新状态属性,则应单独分配。

@user.status = 'active'
save

或者只使用 update_attribute

于 2013-07-26T03:10:13.930 回答