Take the 2-minute tour ×

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
  def down
    drop_table :messages

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')

@m = Message.find(msg1.id)
@m.update_attributes(read_at: Time.now)

I get this outputs:



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!

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

You should run msg1.reload before msg1.read_at


share|improve this answer
Despite @m and msg1 having the same id, using the @m.update_attributes(read_at: Time.now) will update the read_at attribute from @m only. After executing msg1.reload it will update the msg1.read_at value. I don't understand why? Over my Message model making a function to update the attr it doesn't works if I don't use reload at the message it self. Can you explain why? I does work over others attr, only at this one it don't update it self –  fejao Jul 26 '13 at 10:51
add comment

Directly from the documentation.



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


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


@user.status = 'active'

or just use update_attribute

share|improve this answer
add comment

In order to update values, you should use

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

Refer documentation for further details

share|improve this answer
add comment

Your Answer


