How can I add variables to an existing obejct? I have a list of chat rooms and I want to add a new variable for each chat to use at my view:
Example I want to add total users of chat
def index
chats_all = ChatRoom.all
@chats = Array.new
chats_all.each |chat|
chat.total_users = 10
@chats << chat
end
@chats
end
total_users is not an attribute of ChatRoom class.
[EDIT - explaim better after @jvillian great awnser]
I don't want total_users as an attribute of User class.
I just want to add as a variable to use at this one single page. For json rails already let my add new attributes to objects. Just need to use as_json().map and a merge()
Example:
def index
chats = chats.as_json().map {
|chat|
chat.merge(
total_users: 10
}
response = { chats: chats }
render json: response
end
Now I got an json with chats and each chat has total_users attribute.
I want to know if I can do something like this with objects, just add a temporary variable to use at index page.
@chats = {:'1' => {total_users: 10}, ..... Can you explain more?total_users? This seems like it might be an XY problem.@chats.each |chat|and than I display total_users