# Many to many relationship. How to model & view?

**URL:** <https://www.ruby-forum.com/t/many-to-many-relationship-how-to-model-view/118012>\
**Category:** Rails\
**Created:** [October 23, 2007, 11:02am UTC](https://www.ruby-forum.com/t/many-to-many-relationship-how-to-model-view/118012 "2007-10-23T11:02:19Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![eafonsof](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/e/9e8a1a/32.png) [@eafonsof](https://www.ruby-forum.com/u/eafonsof)\
**Post date:** [October 23, 2007, 11:02am UTC](https://www.ruby-forum.com/t/many-to-many-relationship-how-to-model-view/118012/1 "2007-10-23T11:02:19Z")

</div>

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.
