[英]How to create temporary attribute & use that in json reponse in rails active record
I am new to ROR. 我是ROR的新手。 I am having a controller where i am getting the search results in available_users variable..
我有一个控制器,在其中我可以在available_users变量中获取搜索结果。
availble_users //some active record result with id,name & address
available_users.each do |userstatus|
userstatus.class_eval do
attr_accessor :is_friend
end
if current_user.invitations.find_by(:friend_id => userstatus.id) //invitation is another table
userstatus.is_friend = "true"
else
userstatus.is_friend = "false"
end
end
render json: available_users
but when i am getting the response on ajax request it is serving the same array without including is_friend column. 但是,当我收到有关ajax请求的响应时,它正在提供相同的数组而不包含is_friend列。
here is my json response. 这是我的json响应。
id: 2
name: abc
address:
please can anyone figure me out why it is not appending this temporary attribute. 请任何人能弄清楚为什么它不附加此临时属性。 Thanks.
谢谢。
what you have will work if you pass the methods option to_json 如果将方法选项传递给_json,那么您将拥有的东西将起作用
render json: available_users.to_json(:methods => :is_friend)
Or you could do this 或者你可以这样做
available_users.each do |userstatus|
if current_user.invitations.find_by(:friend_id => userstatus.id) //invitation is another table
userstatus["is_friend"] = "true"
else
userstatus["is_friend"] = "false"
end
end
render json: available_users
[]=
is an alias for write_attribute
[]=
是write_attribute
的别名
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.