Create and edit with has_and_belongs_to_many

Damaris Fuentes wrote:

In SQL, abbreviated, I have: CREATE TABLE pages ( id int(10) unsigned ... CREATE TABLE `subjects` ( `id` smallint(5) unsigned NOT NULL auto_increment, `subject` varchar(20) NOT NULL, ... CREATE TABLE `pages_subjects` ( page_id int not null, subject_id int not null,

Okay, so here we have a field called 'subject' in the 'subjects' table...

In the views (_form.rhtml), when creating or editing a page, I have the following text box: <label class="heading" for="page_subjects">Subjects</label><br/> <%= text_field 'page', 'subjects' %>

And what you have asked for here is a text field for the page object. The value of which is to be saved into page.subjects. If you look at the HTML source rails will render you will see the field is called "page[subjects]". If you simply go page.create(params[:page]) in your controller it is going to try and place the value of that text field (which will always be a string) into page.subjects which rails expects to be a collection of Subject objects. The string value actually needs to be added to a new Subject object, and that object then added to the page.subjects collection. So maybe something like:

<%= text_field_tag "subject", "subject" %> or <%= text_field_tag "subject[subject]" %>

and then in the controller:

@subject.create(params[:subject]) @page.create(params[:page]) @page.subjects << @subject

I'll leave you to work out a more elegant solution to preventing duplicate subjects from being created, but hopefully that explains what is happening for you.