@accounts.count,:accounts => @accounts.page(page-6ren">
gpt4 book ai didi

ruby-on-rails - Ruby on Rails "render json:"忽略 alias_attribute

转载 作者:行者123 更新时间:2023-12-04 02:13:28 25 4
gpt4 key购买 nike

我的 account.rb 模型文件中有以下代码:

class Account < ActiveRecord::Base
alias_attribute :id, :accountID
alias_attribute :name, :awzAccountName
alias_attribute :description, :awzAccountDescription
end

index 方法中的以下代码来 self 的accounts_controller.rb 文件:

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 返回一个结果集,其中包含模型文件中定义的 alias_attribute 列名。但是,render :json => {:total => @accounts.count,:accounts => @accounts.page(page).per(items_per_page) } 代码返回的结果集包含原始列名称。有什么方法可以改变这一点,以便使用 alias_attribute 列名吗?

最佳答案

我不希望 render json: @accounts 包含别名属性。 alias_attribute 只是让您可以使用另一个名称来引用属性 - 它根本不会替换原始名称。

如果您确实想在模型的 json 输出中包含别名,您可以覆盖 as_json 并显式添加这些方法:

def as_json(options = {})
options[:methods] ||= []
options[:methods] += [:name, :description]
super(options)
end

(我故意省略了 :id,因为这可能是一种特殊情况 - 不完全确定,目前无法在本地进行测试)

关于ruby-on-rails - Ruby on Rails "render json:"忽略 alias_attribute,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36182882/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com