views:

100

answers:

2

I am kinda new to Rails 2.3.3. This question is kinda simple, I have been tryin to overcome this issue but haven`t been able to.

Database and Model Schema

User (id,name,email)

posts (id,subject,message,user_id)

Can you please temme how to 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 of each individual post ? in the index action.

I hope you guys understood my question

Thanks a lot in advance :)

+1  A: 

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

Kieran Hayes
thanks :)I had a doubt it wouldbe something like that and thanks for answering so fast :)
Mike
You're welcome :-) Check out http://railscasts.com and http://asciicasts.com(text version of railscasts) for really good rails tutorials.
Kieran Hayes
+1  A: 

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
Mike Buckbee