ActiveRecord - 与Select一起使用Include

时间:2017-04-19 10:53:29

标签: ruby-on-rails activerecord

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

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

2 个答案:

答案 0 :(得分:2)

您可以使用as_json

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

答案 1 :(得分:0)

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

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

将您的column names替换为address_column1address_column2,依此类推。

希望这有帮助