views:

57

answers:

1

You can take a look at the app I'm referring to at: http://github.com/585connor/QA

So, I've built this question & answer app... kind of. I can get the answers to be listed on their respective questions but I cannot figure out how to get the user info to be displayed on those questions/answers. For example I'd like to put the username next to each answer and the username next to each question. Also, when viewing the show action of the users controller, I'd like to be able to see a list of that particular user's questions and answers.

There are three tables: questions, answers and users. Can you take a look at the github repository and try to point me in the right direction for what steps I should take/concepts I should learn in order to achieve what I'm trying to do?

+1  A: 

Becase you have a

belongs_to :user

in your question and answer model, you can access the associated user-model by calling .user on a question or answer object:

# controller
@question = Question.find :first

# view
<%= @question.user.name %>

Accessing the user's questions and answers is similar:

# controller
@user = User.find :first

# view
<% @user.questions.each do |question| %>
  <%= question.title %>
<% end %>
Sven Koschnicke
Thanks, do I paste @question = Question.find :firstinto the 'show' action so that it replaces the current @question = Question.find(params[:id])?What does the ".find :first" code mean?
585connor
No thats just an example. .find :first gets the first record from the database. You can leave the show action in the controller as it is and access the user with @question.user in the view.
Sven Koschnicke
Hmm, not working. Okay, so I put <%=h @question.user.login %> (this should show the user's username) in the 'show' view for a question and I get an error that says "undefined method 'login' for nil:NilClass". Any idea what could have gone wrong?
585connor
Then the question has no user associated with it. When creating a question you should save which user created it (in the create-method of the questions-controller). Maybe you should also add a validation to the question model that validates the presence of a user.
Sven Koschnicke
Okay, that sounds like it'll be very helpful to me. Could you help me out with what the code what might look like to save which user created a particular question? Would I add this code below the "@question = Question.new(params[:question])" line or is it just a matter of editing that line?
585connor
You should set the user after creation of the object (which is the line with Question.new). It would be the currently logged in user. How you get the currently logged in user depends on which authentication-system you are using and should be documented in its readme.
Sven Koschnicke
Thank you very much, I seem to have gotten it working. Very much appreciated.
585connor