在我的Rails应用程序中,我有以下代码:
MemAccount
模式
class MemAccount < ActiveRecord::Base
attr_accessor :current_mem
def followstatus
SntFollow.where({:from_id=> current_mem.id}).pluck('to_id').include? id
end
end
控制器:
def search
_items = MemAccount.select(:avatar,:nc,:id,:followers).where("nc like '%#{params[:search]}%'")
render json:{
:items => _items
}.to_json(:methods=>["followstatus"])
end
如何为mem列表设置MemAccount实例attr current_mem
,而不是一个mem.I想找到实现此目的的最佳方式,谢谢!
class MemAccount < ActiveRecord::Base
def followstatus me
SntFollow.where({:from_id=> me.id}).pluck('to_id').include? id
end
end
def search
_items = MemAccount.select(:avatar,:nc,:id,:followers).where("nc like '%#{params[:search]}%'")
render json:{
:items => _items
}.to_json(:methods=>["followstatus(#{current_mem})"])
end
但结果如下:
{"items":[{"avatar":"tx.png","nc":"","id":1,"followers":1}...]}
我找不到attr followstatus
,为什么?
答案 0 :(得分:0)
为什么不根据需要使用https://github.com/rails-api/active_model_serializers来序列化对象。它方便,非常有帮助。并使用针对respond_with
respond_to
和format.json
您可以将序列化器创建为
class AccountSerializer < ActiveModel::Serializer
attributes :name, :method_name, :instane_method_name
def method_name
"value"
end
end
并在控制器中
respond_with @accounts, each_serializer: AccountSerializer