0

I've got a posts model and of course authors which is a foreign key relationship to my users.

I am trying to output in JSON, the posts with the authors names. I know this is rails 101, but I can't call post.author because I'm not in a view.

I've tried doing this a few ways, but none seem to be working.

My post model has

 belongs_to :user, :foreign_key => :author_id

def post_author
 self.each {|a| a['author'] = User.find(a.id)}
end

in my controller I've tried all sorts of

posts=Post.find(:all).includes(:user)

#or
posts=Post.find(:all).includes(:post_author) #don't think this is right anyway, but tried 

#and 
posts = Post.find(:all)
posts = JSON::Parse(posts.to_json()).merge('author'=>posts.author) #or posts.user, etc etc

of course, none of these have worked, which is why I'm posting here. What's the best way to get the author of a post.

----------------------update ---------------------------

@rjz provided a response which works, but I'm hoping isn't the best way. He suggested using

posts.to_json(:include=> :user,:only[:username])

this meant I was only getting the username back, but I need more than that so I started using :except instead. The problem here is that I've got a fields like id which I need in the post, but not in the author, but if I exclude them in this manner, the field is excluded from the results completely. I'm also having to list out each field I need, and I'm not sure if that is the best way.

1 Answer 1

1

You might have to tease the name of your association a bit to get exactly what you want, but what you're looking for is the :include option when you serialize with to_json:

posts.to_json(:include => :user)
Sign up to request clarification or add additional context in comments.

3 Comments

that gets me the user @rjz, but brings up the new problem of now returning everything, including email, etc. I tried posts.to_json(:include => :user, :select => :username), but that didn't work. can I mix a select in with this?
Not exactly, but you can use the :only option in to_json to limit what fields get serialized. It's detailed in the documentation I linked above.
Thanks rjz, this is an ok, solution. I'm using :except for now, but I'm having to either remove or add all the fields for both tables. I'm hoping there may be a better way, and I'll update the question. If there isn't a better response, the answer is yours. thanks again

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.