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
。有没有办法做到这一点,以便查询本身只选择所需的列。
答案 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_column1
,address_column2
,依此类推。
希望这有帮助