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.