I am creating a instance variable that gets passed to my view. This variable ‘post’ has a user_id associated with it and I wanted to add an extra attribute called ‘username’ so I can also pass that and use it in the view.
Here is an example of what I would like to do.
@post = Post.find(params[:id])
@post.username = User.find(@post.user_id).username
A username column does exist on my Users model but not my Songs model. So it won’t let me use
@post.username
I know I can just make an entirely new instance variable and put that information in there but I would like to keep everything nice and neat, in one variable. Which will also make my json rendered code look cleaner.
Any ideas on how I can accomplish this?
Thanks!
Based on the presence of a
user_idin yourPostmodel, you probably already have an association set up that can retrieve the username. It will probably save a lot of trouble to simply use the existing association:If you’re likely to be querying more than one post at a time (e.g., on an index page, calling
.includesto tell Rails to eager-load an association will help you avoid the N+1 problem:Finally, to include the associated record in your JSON output, pass the
:includeparameter as you serialize:This question includes a much more comprehensive discussion of serialization options. Well worth a read.