Ruby on Rails Friday, August 31, 2012

On 31 August 2012 16:26, Nate FT <lists@ruby-forum.com> wrote:
> 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.

@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

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.

No comments:

Post a Comment