I have a class persons and a class subjects. at the moment they are not connected at all. As a user one can only chose subjects from a list and inspect them. Now I'd like to allow users to assign to subjects, thus the user class needs a list where it can store its subjects. ... and a table which maps subjects to persons.. (m to n)
I have not much experience with Ruby on Rails and I am afraid to destroy my application when trying to do this.
So far I found out that there are commands to do that (sth. like $ rails generate migration AddSubjectsToPersons
), but I can't find out what they do exactly, e.g.if it touches my model or controller classes..
In case that yes - is there something removed I wrote before?, if not - is it enough to add a field (a list) called lessons to my model and the connection to the db will be detected automatically?
I generated a migration file using the command rails generate migration CreatePersonsSubjects
. The names are put together in alphabetical order (convention).
The result of this command is an skeleton in which code can be entered to change database tables.
This went to the "up" part:
create_table :persons_subjects, :id => false do |t|
t.integer :person_id, :null => false
t.integer :subject_id, :null => false
end
In the "down" part these actions can be reverted:
drop_table :persons_subjects
Finally I added a field in the person class (and only to the person class, by the way. But one could/should also add a similar line to the subject). The name is convention too.
has_and_belongs_to_many :subjects
The subjects can be used for example like this in the view:
<div>Courses taken:
<ul>
<% @person.subjects.each do |subject| %>
<li><%= link_to subject.name, subject, :class => 'action' %></li>
<% end %>
</ul>
</div>