Rails使用模型关联在json中呈现对象

时间:2018-03-12 05:20:33

标签: ruby-on-rails

我正在尝试使用帖子模型呈现用户模型,但我无法弄清楚它的语法是什么

class Post < ApplicationRecord
   belongs_to :user
end

class User < ApplicationRecord
   has_many :posts, dependent: :destroy
end

控制器

  def map_locations
    @posts = Post.where.not(location: [nil, ""])
    render :json => @posts.as_json(only: [:topic, :location, :latitude, :longitude],)
  end

输出:

[{"topic":"Garret ATX","location":"Hornitos, CA, USA","latitude":37.5021592,"longitude":-120.238241}]

期望的输出:

[{"user_name":"Randy","topic":"Garret ATX","location":"Hornitos, CA, USA","latitude":37.5021592,"longitude":-120.238241}

用户模型有@ user.user_name,这是我每个帖子所需要的。 如何呈现与每个帖子关联的用户?

1 个答案:

答案 0 :(得分:1)

我希望这有效

def map_locations
  @posts = Post.where.not(location: [nil, ""])
  render :json => @posts.as_json(:only => [:topic, :location, :latitude, :longitude], :include => {:user => {:only => :user_name}})
end

请查看apidock了解详情。