Newbie Q: How to find the user that the question belongs_to

I have a User and a Question model, User has_many questions and Question
belongs_to user.

On my question show page, I show a question, along with the name of the
user who’s asking the question.

Everything seems to be working fine, but my controller looks like this:

questions_controller.rb
.
.
.
def show
@question = Question.find(params[:id])
@user = User.find(@question.user_id)
end

I know rails must have a less messy way to figure out which user the
question belongs to. I’ve read that using something like question.user
would give me what I need, but I can’t figure out how to implement it in
my controller.

Sorry for the simple question, any suggestions are appreciated. Thanks!

On 31 August 2012 16:26, Nate FT [email protected] wrote:

.
my controller.
@user = @question.user
but in fact there is no need to do that in the controller. In the
view just use @question.user.name or whatever it is. That assumes
that every question will have a user, if there is any chance that a
question will not have a user then @question.user.name would fail as
user would be nil, so you would have to cope with that.

Since you are asking the question I suggest that you work through a
good tutorial which would give the basics of rails. railstutorial.org
is good and is free to use online.

Colin

I guess you are looking for this or probably i misunderstood your
question
def show
@question = Question.find(params[:id])
@user = @question.user
end

On Fri, Aug 31, 2012 at 8:56 PM, Nate FT [email protected] wrote:

.
my controller.
To unsubscribe from this group, send email to
[email protected].
For more options, visit https://groups.google.com/groups/opt_out.


Thanks,
Aash

Hai!

This tutorials is help for you …

Active Record Associations — Ruby on Rails Guides

by
bdeveloper01