【问题标题】:ActiveRecord - Use Include together with SelectActiveRecord - 将 Include 与 Select 一起使用
【发布时间】:2017-04-20 16:13:12
【问题描述】:

client.rb

class Client < ApplicationRecord
    belongs_to   :address
end

address.rb

class Address < ApplicationRecord
    has_one :state
    has_one :country
end

来自Client#show 我想返回一个包含客户端详细信息及其地址的 JSON。但是,address 中有一些我不想返回的字段(例如 created_at、updated_at)。

我写这个来渲染 JSON -

def show
   @client = Client.select("id, address_id").first
   render json: underscore_to_camel(@client.as_json(:include => :address))
end

就像我将select 用于Client 我如何将它用于Address

编辑

如果我使用@client.as_json(include: {address: { except: [:created_at, :updated_at]}}),则生成的哈希没有created_at

但是当查询运行时,它会在addresses 上执行select *。有没有办法做到这一点,以便查询本身只选择所需的列。

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

    你可以使用as_jsonexcept选项

    render json: underscore_to_camel(@client.as_json(include: {address: { except: [:created_at, :updated_at]}}))
    

    【讨论】:

    • 这确实有效。但它仍然从数据库中获取所有列。有没有办法可以在数据库查询级别限制列?喜欢select
    • @mridula 哪个表的所有列?
    • @mridula 你能把渲染后的json贴在这里吗?
    • 抱歉,我现在不能发布 JSON。我可以稍后发布。 addresses 表的所有列。
    • 来自 rails 日志:Client Load (1.2ms) SELECT id, address_id, name, default_language, main_phone, contact_person_name, contact_person_email, contact_person_phone, website, notes FROM "clients" ORDER BY "clients"."id" ASC LIMIT $1 [["LIMIT", 1]]Address Load (19.9ms) SELECT "addresses".* FROM "addresses" WHERE "addresses"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
    【解决方案2】:

    您可以使用only 选项从表中选择特定列

    render json: underscore_to_camel(@client.as_json(include: {address: { only: [:address_column1, :address_column2, ...]}}))
    

    将您的column names 替换为address_column1address_column2 等。

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 2018-09-30
      • 1970-01-01
      • 1970-01-01
      • 2015-12-02
      • 2020-02-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多