0
votes

Rails 2.3.3

Database and Model Schema

User (id,name,email)

posts (id,subject,message,user_id)

How can I display the name of the user who has created a particular post?

#posts controller
#index action - retrieves all posts in descending order. 
#I also want it to retrieve user information of that post

def index
    @posts = Post.all( :order => "created_at DESC")
    respond_to do |format|
      format.html
    end
end
#partial _post.html.erb

Posted by "??how can show the user name here??"

I have modified the user.rb and post.rb with active record associations and have set a foreign key. i.e post.user_id references user.id.

But how can I display user information for each individual post in the index action?

3

3 Answers

2
votes

<%=post.user.name %> given that the post record has a valid user_id stored.

1
votes

I'd frame the bigger version of your question as: "How can I sort out relationships between models in my Ruby on Rails app?"

What I've found most helpful for that is using "script/console" to explore what's available.

In your terminal, cd to your rails root and enter "script/console" this will launch a new command line that you can create objects in.

In this circumstance, you could enter something like the following to sort out what's available.

p = Post.find(:first)

p.user

p.user.name
0
votes

You can check with this in your rails console. Post.first.user.name

You want to display it in view then, @posts.each do |post| <%= post.user.name %> end

Hope it will helps.