I’m trying to encode an array of model objects to JSON, including data related through association. But the foreign key field in my schema is not modelname_id, so I can’t simply do ActiveSupport::JSON.encode(xxx,:include=>{:modelname}). The reason for this schema difference is something I feel should be common. So there might be an established best practice, but I don’t know that.
relevant migration file:
def self.up
create_table :tables do |t|
t.integer :room_id
t.integer :table_num
t.integer :user_1_id
t.integer :user_2_id
t.timestamps
end
end
Since each table can have two users sitting down, I can’t simply use user_id, but had to use user_1_id and user_2_id
Now, suppose I have an array of tables I want to encode to json, along with it I want each table object to include user_1_email:’xxx’ and user_2_email:’xxx’ fields. How can I do that?
Also, when I search for ActiveSupport::JSON.encode in various online documentation, I cannot find anything written on what I can do with options.
For instance, the api in
http://api.rubyonrails.org/
only tells me the default option parameter is nil, but doesn’t say anything about what options I can use. Am I missing something?
On a side note, can I also add non-model attributes in JSON encoding?
I’ve been searching for a way for a few days but can’t find anything.
You can easily customize and extend the JSON representation of an object by implementing a custom
#as_jsonmethod.Example: