Rails to_json 包含一个有参数的方法
Rails to_json include a method has args
在我的 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 实例属性 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}...]}
我找不到属性 followstatus
,为什么??
为什么不使用 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
在我的 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 实例属性 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}...]}
我找不到属性 followstatus
,为什么??
为什么不使用 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