开发者

Attribute Not Being Added to Object

I'm trying to add an attribute to a model object. Direct access works but when I print the entire object or encode it into JSON, that attribute is left out. Can someone tell me what I'm doing wrong?

Here is my 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 is my 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 = ? AND id > ?",room_id,message_id)
  end
end

edit:

Here is the migration file for chat_messages table. I'm not really looking to save sender_nickname. So it's more like a virtual attribute (but is still in db through association). And I might need to add 开发者_如何学Goother attributes later that aren't in the db. Is it possible to do it without using association?

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

    t.timestamps
  end
end


as far as I know to_json will only take the attributes in the model and serialize (as in chat_message.attributes, not attr_accessor).

You properbly got a sender, or user model, or anything like that.

What I would do is to make a relation to the sender, user or what its called, with a belong_to, and then use this code to convert it to json:

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

It may also work with you code, and then just:

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

There also some documentation here: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html

Hope it helps :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜