Many to many relationship. How to model & view?

Hi there, I’m having a hard time to properly define things for an
application that has Users, Questions and Answers.
Questions contains all questions any user can answer.
Answers contains the specific answers provided by each user for some
or all questions.
Some Users could have answered to only some questions or none or all
of them. So, the number of Answers entries associated with the User is
variable.

I have the following tables/models:

Table users (id, name, etc)
Table questions (id, question, position)
Table answers (id, answer, question_id, user_id)

class User < ActiveRecord::Base
has_many :answers, :dependent => true
has_many :questions, :through => :answers

end

class Question < ActiveRecord::Base
has_many :answers, :dependent => true
has_many :users, :through => :answers
end

class Answer < ActiveRecord::Base
belongs_to :user
belongs_to :question, :order => ‘position’
end

I was able to show all questions (with answers) associated with a
specific user with the following (view) code:

Controller:
@user = User.find(params[:id])

View:
<% @user.answers.each do |answer| %>
<%= answer.question.question %> - <%= answer.answer
%>
<% end %>

Now, I wanted to be able to add/edit answers to some/all questions
using one single view. Is that possible?
What would be the code (controller, view, etc) to perform that? Do I
need to change tables/models?

Now, a more generic question: how can I manipulate a many to many
relationship between two tables where I need to have extra attributes
in the table that connects them (say, the “answers” table)?
By this question I mean, how to I add rows to the “answers” table?

Any help will be very appreciated.
Eduardo.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs