Topic: Associations between 2 tables

Hi,

sorry for this n00b question but I'm totaly new to rails and I need some help on something.

I'm building a simple contact application. So in my DB I have a contact table. Every contact can have more then one note. So I have a note table. Those 2 are related to eachother with an id. So every note record has a contact id.

My 2 models look like this

class Contact < ActiveRecord::Base
  has_many :notas
end

class Nota < ActiveRecord::Base
  belongs_to :contact
end

A user can edit/add a note on the contact edit view. The code for my edit view looks like this

  def edit
    @contact = Contact.find(params[:id])

    @functions = Function.find(:all, :order => "id")
    @countries = Country.find(:all,:order => "iso")
  end


That all works fine. So I display this all onto my view. (I will only show the relevant code)
<script>
    function addDiv(frm) {

        document.getElementById('readroot').style.display='block'
        var newFields = document.getElementById('readroot').cloneNode(true);
        document.getElementById('readroot').style.display='none'
        newFields.id = '';
        newFields.style.display = 'block';
        var newField = newFields.childNodes;

        var insertHere = document.getElementById('container');
        insertHere.parentNode.insertBefore(newFields,insertHere);
    }
</script>

.......

<%
if(@contact.notas)
    @contact.notas.each do |nota| %>
<textarea cols="40" id="contact_note" name="contact[note]" rows="3" >
  <%= nota.nota %>   
</textarea>    <br>
<% end end %>


<div id="readroot" style="display:none;">
<p><textarea cols="40" id="contact_note"
name="contact[note]" rows="3" ></textarea></p>
</div>
<div id="container"></div>
<input type="button" value="Add a note" onclick="addDiv();" /><br /><br />


So far so good. I can see all the notes on my edit screen. But now comes my problem. If I hit the save button, my edited or new notes aren't being saved. This is probably due to the fact that my update method isn't complete

  def update
    @contact = Contact.find(params[:id])
   
    if @contact.update_attributes(params[:contact])
      flash[:notice] = 'Contact was successfully updated.'
      redirect_to :action => 'show', :id => @contact
    else
      render :action => 'edit'
    end
  end

The problem is that I don't know where to begin to tackle this. I'm reading a lot on Rails in a quick pace, but I need to find a solution for this.So if a good soul could help me out on this one, it would realy mean a lot to me.

I whas thinking about a solution like working on the notes separatly and include the view stuff with a partial in the contact view, but even there I have no id where to start.

Sorry for this long post but I hope a good soul will find the will to read this all and maybe help me out.

Greetz and thanks in advance.

Last edited by D@ Mick (2007-09-09 05:15:56)

Re: Associations between 2 tables

No one who can point me in the right direction?

Re: Associations between 2 tables

This is the same problem I'm having.  I can add to my "child" model during a create, but when I try to edit and update the "child" models in my one form, nothing gets updated.  I would love someone to point us in the right direction.  Until then, I'll keep scouring this board......

Last edited by shaggy (2007-09-13 10:45:52)

Re: Associations between 2 tables

Let me know when you would find something interesting. I'm still searching for a solution but in the meantime I just split the 2 forms up. But it's not a pritty way to go. If I stumble on anything usefull, I'll post it here

Re: Associations between 2 tables

It looks like there's a typo in your class name...

Your class name is Nota...

class Nota < ActiveRecord::Base
  belongs_to :contact
end

but in your _form it's written as contact[note]
<div id="readroot" style="display:none;">
<p><textarea cols="40" id="contact_note"
name="contact[!!!!note!!!!!]" rows="3" ></textarea></p>
</div>

when it should be name=contact[nota].

Make sure everything is working in your models first, open up a ruby console (ruby script/console) and test:

c = Contact.new(...)
n = Nota.new(...)
c.notas << n
c.notas.each do |nota|
  nota
end

Re: Associations between 2 tables

Thank you for pointing that out to me scott32. Nothing more embarrassing than making such a typo in your code. But unfortunaly the problem remains.
But I did get an error on this one: undefined method `nota=' for #<Contact:0x47b5ad0>

That is probably due to the fact that there isn't anything pointing to Nota from the Contact point of view. It is in the Nota table that I make a reference to a contact.

So the thing I would need to do is tell RoR to store the notas in the nota table with the right contact id rather then to store it in the contact table.

Re: Associations between 2 tables

Hey shaggy,

I found a solution. It whas pritty dumb not to think about it, but you can achieve the same by using the same method you would in PHP.

When you post your form, you get redirected to the proper method of your parent controler to save/update the object. In your save/update method, just save your parent object the way you normally would. Then come the child objects. Keep in mind that RoR sends your input fields as a hash. So to update all your childs you can work like this

params[:your fieldname].each do |field_id, field_content|
    Nota.find(nota_id.to_i).update_attribute ....
end

For your new childs you can apply the same thing, only diffrence is that your id will be empty and you need to save them instead of updating.

Hope it will help you