Rails json包含2个相同模型的实例

时间:2019-01-02 18:58:30

标签: ruby-on-rails

我有一个称为Exchange的模型,该模型存储创建它的用户的user_id。我可以打电话给@exchange.user,它返回User.where(user_id: @exchange.user_id)

还有一个关联关系,显示所有喜欢Exchange的用户,可以用@exchange.favorite_users

进行调用

我想在json响应中返回这两个值,但仅返回第一个。

@exchanges = Exchange.includes(:tags, :favorite_users, :user).where(approved: true)

 respond_to do |format|
   format.json { render json: {data: {exchanges: @exchanges.to_json(include: [:tags, user: {:only => [:id,:slug], :methods => [:avatar_url]}, favorite_users: { only: [:id]}] ), tags: @tags.to_json }}}
 end

此版本返回user: {:only => [:id,:slug], :methods => [:avatar_url]},但不返回favorite_users: { only: [:id]}

format.json { render json: {data: {exchanges: @exchanges.to_json(include: [:tags, favorite_users: { only: [:id]}, user: {:only => [:id,:slug], :methods => [:avatar_url]}] ), tags: @tags.to_json }}}

此仅返回favorite_users: { only: [:id]},但不返回user: {:only => [:id,:slug], :methods => [:avatar_url]}

我怎么都退货?

交换模型

class Exchange < ApplicationRecord
  belongs_to :language
  belongs_to :user
  has_many :exchanges_users
  has_many :favorite_users, :through => :exchanges_users, source: :user
  has_many :tags_exchanges
  has_many :tags, :through => :tags_exchanges
end

1 个答案:

答案 0 :(得分:1)

@exchanges.to_json(include: [
    :tags, 
    {user: {only: [:id,:slug], methods: [:avatar_url]}}, 
    {favorite_users: { only: [:id]}}
])

如果要返回两个关联模型,请使用{}

来包装关联

Brakets仅使用关联符号,而不能使用选项