首页 > Rails输出nested 在jbuilder模板里面如何设置特定的字段

Rails输出nested 在jbuilder模板里面如何设置特定的字段

比如这个模板

json.extract! @category, :id, :subject, :articles , :description, :created_at, :updated_at

其中articles是一个 many to one :category的model
然后如果按默认的输出

我检索一个category 就会把关联的articles也一起输出了 而且是 article的所有字段 包括正文 .

如何选择 articles输出的字段呢

我只需要articles的id subject 以及 preview , 我在stackoverflow上搜了 居然没找到


这个是一个非常简单的日常使用需求
在jbuilder的README.md中,第一段示例展示了用法
可能这也是你在stackoverflow上找不到答案的原因了
使用gem,要从gem本身提供的信息中去获取方案,不要养成基本的用法也去QA的习惯。

json.content format_content(@message.content)
json.(@message, :created_at, :updated_at)

json.author do
  json.name @message.creator.name.familiar
  json.email_address @message.creator.email_address_with_name
  json.url url_for(@message.creator, format: :json)
end

if current_user.admin?
  json.visitors calculate_visitors(@message)
end

json.comments @message.comments, :content, :created_at

json.attachments @message.attachments do |attachment|
  json.filename attachment.filename
  json.url url_for(attachment)
end
【热门文章】
【热门文章】