0

I'm trying to render the user model along with the posts model, but I'm having trouble figuring out what the syntax for it would be

class Post < ApplicationRecord
   belongs_to :user
end

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

Controller

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

Output:

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

Desired Output:

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

The user model has @user.user_name which is the one I need for each post. How do I render the user associated with each post?

1 Answer 1

2

I hope this works

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

Please check the apidock for more details.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.