Question

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!

Was it helpful?

Solution

You should run msg1.reload before msg1.read_at

or

msg1.reload.read_at

OTHER TIPS

In order to update values, you should use

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

Refer documentation for further details

Directly from the documentation.

Use attr_accessible to prevent mass assignment (by users) of attributes that should not be editable by a user. Mass assignment is used in create and update methods of your standard controller.

For a normal user account, for example, you only want login and password to be editable by a user. It should not be possible to change the status attribute through mass assignment.

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

So, doing the following will merrily return true, but will not update the status attribute.

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

If you want to update the status attribute, you should assign it separately.

@user.status = 'active'
save

or just use update_attribute

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top