ruby - Attribute Not Being Added to Object -


i'm trying add attribute model object. direct access works when print entire object or encode json, attribute left out. can tell me i'm doing wrong?

here rails console output:

irb(main):010:0> b=chatmessage.new(:user_id=>4,:room_id=>1,:message=>"hello world") => #<chatmessage id: nil, room_id: 1, user_id: 4, message: "hello world", created_at:     nil, updated_at: nil> irb(main):011:0> b.sender_nickname="bbb" => "bbb" irb(main):012:0> b.sender_nickname => "bbb" irb(main):013:0> b => #<chatmessage id: nil, room_id: 1, user_id: 4, message: "hello world", created_at: nil, updated_at: nil> 

here model code:

class chatmessage < activerecord::base   attr_accessor :sender_nickname    def self.get_last_message_id     last_message=chatmessage.all.last     last_message.nil? ? 0 : last_message.id   end    def self.get_all_messages_after(room_id,message_id)     chatmessage.where("room_id = ? , id > ?",room_id,message_id)   end end 

edit:

here migration file chat_messages table. i'm not looking save sender_nickname. it's more virtual attribute (but still in db through association). , might need add other attributes later aren't in db. possible without using association?

def self.up   create_table :chat_messages |t|     t.integer :room_id     t.integer :user_id     t.string :message      t.timestamps   end end 

as far know to_json take attributes in model , serialize (as in chat_message.attributes, not attr_accessor).

you properbly got sender, or user model, or that.

what make relation sender, user or called, belong_to, , use code convert json:

chat_message.to_json(:include => { :sender => { :only => :nickname } }) 

it may work code, , just:

chat_message.to_json(:include => { :sender_nickname }) 

there documentation here: http://api.rubyonrails.org/classes/activemodel/serializers/json.html

hope helps :)


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -