Topic: Problem using a one-to-many relationship

I have a problem using a one-to-many relationship in my ruby code.
Yes, I have searched through this forum and many others to get the exact changes I need to make to my code to get the whole thing working but could not find a correct one to go with.

Here is my set up so far -
1. Have 2 models - person and role. The person and role have a many-to-one relationship with the person.role_id pointing to
2. Made changes in the two models like this.

   person.rb ---> belongs_to :role.role_id;
   role.rb --->has_many :person;

3. I want to show the roles when creating a person, so I added this code in my _forms.rhtml of person view.
   <p><label for="person_role">Role</label><br/>
     @roles = Role.find(:all, :order => "id")
     collection_select(:role, :name, @roles, :id, :name)

4. The drop down appears all right, but when creating a person, the role_id goes as NULL so i am not able to associate a person to a role.

Any ideas on what else I should be doing to get this working.?


Re: Problem using a one-to-many relationship

I am new too and this stuff frustrates me to no end. Seems like documentation on this simple stuff is somewhat lacking.
I admit I'm a noob.

I'm assuming  you can do it this way in the first place. I have only done this with the MVC in place. Doesn't look like you're doing it that way...

but I think In your collection select it should be

collection_select(:person, :role_id, @roles, :id, :name)

Also it would be the plural of person... not sure if thats people for you.

You might want to set this up with the controller pulling the data for you... also you might need to add a @person = Person.find(:all) too.

Last edited by engineerDave (2008-06-28 06:50:27)

"If I'd asked my customers what they wanted, they'd have said a faster horse." - Henry Ford

Re: Problem using a one-to-many relationship

I got the same problem.
I followed the Netbeans doc (Building Relationships Between Rails Models) but can't get the post_id.
It just insert the comment but with a post_id NULL.

Any idea?