ChrisBedoya
ChrisBedoya

Reputation: 747

"Post" posted by "User" association

I want to be able to associate a Post with the User that created the post.

So far I have:

belongs_to :user in my post.rb

and

has_many :post in my user.rb

I know I have to add something to my posts controller but I dont know what. I want each of my posts to have a "Posted by: (user info here)"...

Any help? Thanks in advance.

Upvotes: 0

Views: 4365

Answers (2)

Mike Lewis
Mike Lewis

Reputation: 64137

You can access the user by doing:

@post.user

So you might have:

Posted By: <%= @post.user.username %>

where @post is the variable where the post exists.

You can read up on assocations in rails here, and more specifically in your case here

To answer your question, no you don't need to do anything to your controllers for this functionality to work.

Upvotes: 2

Ryan Bigg
Ryan Bigg

Reputation: 107718

You can reference this association using the user method defined on Post objects by the belongs_to:

<%= post.user.name %>

You can read more in the associations guide.

Upvotes: 0

Related Questions