views:

26

answers:

1

I have 3 models with the following associations. A model Question belongs to a particular user and has many answers, an Answer model belongs to both a user and a question. A user model therefore has many questions and answers. My answer model has the fields User_id and question_id which identifies the owner of the question the answer is posted to and who created or owns that question. So how do I assign the user and question ids to the answer on my create action and what is the structure of the link on my view for posting an answer. Another question is, is this the best way to go about it. My aim is to display the users questions and answers on the user dashboard such that if a user views a question he can see answers to that question and vice versa.

A: 

Short answer:

Answer.create(params[:answer].merge(:question_id => @question.id, :user_id => @user.id)

or

@question.asnwers.create(params[:answer].merge(:user_id => @user.id)

or

@user.answers.create(params[:answer].merge(:question_id => @question.id)

Long answer, I'm assuming you can get the logged in user, and you have the routing defined as:

map.resources :questions, :has_many => [:answers]

So your routes are like: example.com/questions/:question_id/answers. And then you do in the controller @question = Question.find(params[:question_id])

I don't understand what you mean by structure of the link for posting a new answer. First you need a link to new, something like link_to('New answer', new_question_answer_path(@question)).

Then, in the controller:

def new
  @question = Question.find(params[:question_id])
  @answer = Answer.new
end

In the view for new:

<% form_for :answer, [@question, @answer] do |f| %>
  Your form stuff
<% end %>

And then you would have the create action... I haven't tried this code, but you get the idea, right?

jordinl