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!
.
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.