Ruby Rails "render json:" 忽略 alias_attribute
Ruby on Rails "render json:" ignoring alias_attribute
我的 account.rb 模型文件中有以下代码:
class Account < ActiveRecord::Base
alias_attribute :id, :accountID
alias_attribute :name, :awzAccountName
alias_attribute :description, :awzAccountDescription
end
以及我的 accounts_controller.rb 文件中 index 方法中的以下代码:
def index
@accounts = Account.all
if params["page"]
page = params["page"]
items_per_page = params["per_page"]
render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) }
else
render json: @accounts
end
end
正如预期的那样,render json: @accounts
returns 结果集包含模型文件中定义的 alias_attribute
列名称。但是,render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) }
代码 returns 包含原始列名称的结果集。有什么方法可以更改它以便使用 alias_attribute
列名称?
我根本不希望 render json: @accounts
包含别名属性。 alias_attribute
只是让您可以使用另一个名称来引用属性 - 它根本不会替换原始名称。
如果您确实想在模型的 json 输出中包含别名,您可以覆盖 as_json
并显式添加这些方法:
def as_json(options = {})
options[:methods] ||= []
options[:methods] += [:name, :description]
super(options)
end
(我故意省略了 :id
,因为这可能是一种特殊情况 - 不完全确定,目前无法在本地进行测试)
我能够通过覆盖 serializable_hash
方法来解决这个问题。
def serializable_hash(options = {})
options[:methods] ||= []
options[:methods] += [:name, :description]
super(options)
end
您可以通过将 methods
参数传递给 as_json
来获得相同的结果,而无需更改模型的默认序列化。像这样:
render json: @accounts.as_json(methods: [:name, :description])
我的 account.rb 模型文件中有以下代码:
class Account < ActiveRecord::Base
alias_attribute :id, :accountID
alias_attribute :name, :awzAccountName
alias_attribute :description, :awzAccountDescription
end
以及我的 accounts_controller.rb 文件中 index 方法中的以下代码:
def index
@accounts = Account.all
if params["page"]
page = params["page"]
items_per_page = params["per_page"]
render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) }
else
render json: @accounts
end
end
正如预期的那样,render json: @accounts
returns 结果集包含模型文件中定义的 alias_attribute
列名称。但是,render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) }
代码 returns 包含原始列名称的结果集。有什么方法可以更改它以便使用 alias_attribute
列名称?
我根本不希望 render json: @accounts
包含别名属性。 alias_attribute
只是让您可以使用另一个名称来引用属性 - 它根本不会替换原始名称。
如果您确实想在模型的 json 输出中包含别名,您可以覆盖 as_json
并显式添加这些方法:
def as_json(options = {})
options[:methods] ||= []
options[:methods] += [:name, :description]
super(options)
end
(我故意省略了 :id
,因为这可能是一种特殊情况 - 不完全确定,目前无法在本地进行测试)
我能够通过覆盖 serializable_hash
方法来解决这个问题。
def serializable_hash(options = {})
options[:methods] ||= []
options[:methods] += [:name, :description]
super(options)
end
您可以通过将 methods
参数传递给 as_json
来获得相同的结果,而无需更改模型的默认序列化。像这样:
render json: @accounts.as_json(methods: [:name, :description])