# Has\_many and belongs\_to example?

**URL:** <https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622>\
**Category:** Rails\
**Created:** [March 4, 2006, 10:20am UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622 "2006-03-04T10:20:36Z")\
**Posts on this page:** 6\
**Page:** 1

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 4, 2006, 10:20am UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/1 "2006-03-04T10:20:36Z")

</div>

Hi!

If i have 2 tables i.e. product and images and product has\_many images,  
image belongs\_to product - how to create \_form.rhtml, new/create and  
edit/update methods in product controller, so in a single form i can add  
one product and MANY (let’s assume for now that this number is fixed)  
images for this product?

Pleeeeease help me 🙂

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 4, 2006, 1:12pm UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/2 "2006-03-04T13:12:24Z")

</div>

g0nzo wrote:

> Hi!
> 
> If i have 2 tables i.e. product and images and product has\_many images,  
> image belongs\_to product - how to create \_form.rhtml, new/create and  
> edit/update methods in product controller, so in a single form i can add  
> one product and MANY (let’s assume for now that this number is fixed)  
> images for this product?
> 
> Pleeeeease help me 🙂

Here are some snips that worked for me (thanks to the guys here);

CREATE TABLE cvs(  
id INT not null AUTO\_INCREMENT PRIMARY KEY,  
first\_name VARCHAR(30) not null,  
family\_name VARCHAR(30) not null,  
.  
.  
updated\_on timestamp(14) not null  
);

drop table if exists skills;  
CREATE TABLE skills(  
id INT not null AUTO\_INCREMENT PRIMARY KEY,  
title VARCHAR(20) not null,  
detail VARCHAR(200) not null,  
cv\_id int not null,  
created\_on timestamp(14) not null,  
updated\_on timestamp(14) not null,  
constraint fk\_skills\_cv foreign key (cv\_id) references cvs(id)  
);

The at the command line;  
script/generate model CV  
script/generate model Skill

(in addition I generated controller & scaffold for each just to get  
going;  
script/generate controller CV\_admin  
script/generate controller Skill

script/generate scaffold CV CV\_admin  
script/generate scaffold skill skills  
)

Then edit the 2 models created;  
class CV \< ActiveRecord::Base  
has\_many :skills  
end

class Skill \< ActiveRecord::Base  
belongs\_to :cv  
end

to get the skills to be created from within the CV form;

## Skills
 \<% for skill in @cv.skills %\> 

**\<%= h(skill.title) %\>**\<%= h(skill.detail) %\>

 \<% end %\>
\<%= link\_to "add\_skill", :controller =\> "skills", :action =\> "new", :id =\> @cv %\>

Inside the skills controller;

def new  
@session[:cv\_id] = params[:id]  
@skill = Skill.new  
end

def create  
@cv = Cv.find(@session[:cv\_id])  
@cv.skills \<\< Skill.new(params[:skill])  
if @cv.save  
flash[:notice] = ‘Skill was successfully created.’  
redirect\_to :action =\> ‘show’, :controller =\> ‘cv\_admin’, :id =\>  
@cv  
else  
render :action =\> ‘new’  
end  
end

the @cv.save updates both the skills list and the cv and takes care of  
all the associations for the foreign keys.

good luck.

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 4, 2006, 11:15pm UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/3 "2006-03-04T23:15:44Z")

</div>

g0nzo wrote:

> Thanks!!!
> 
> But one question: you have separate form for adding skills?  
> Would it be possible to add (many) skills directly via CV form, without  
> using separate form just for skills?

I believe so… I would just put the code from the new & create methods  
for skills (from my example) into those for cv & obviously put the  
skills form in the cv form, but having not tried this yet & as a newbie  
myself, let me know how it works…

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 4, 2006, 8:35pm UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/4 "2006-03-04T20:35:12Z")

</div>

Thanks!!!

But one question: you have separate form for adding skills?  
Would it be possible to add (many) skills directly via CV form, without  
using separate form just for skills?

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 13, 2006, 8:43pm UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/5 "2006-03-13T20:43:04Z")

</div>

# I believe you are doing the same thing I had to do for a person having multiple visits for a given program. I am using AJAX links to add and remove visits. My form looked like this…

\<% unless @pgm\_update.pgm\_visits.empty? -%\>  
\<% @pgm\_update.pgm\_visits.each\_index do |index| %\>

  
  
  
  
  
  
  

| \<%= plus\_one(index) %\>. &nbsp; | Start:   
  
End: | \<%= date\_select “pgm\_visit#{plus\_one  
(index)}”,“start”, :start\_year =\> @program.start\_date.year, :end\_year  
=\> @program.end\_date.year + 1, :order =\> [:month, :day, :year] %\>  
  
\<%= date\_select “pgm\_visit#{plus\_one  
(index)}”,“ends”, :start\_year =\> @program.start\_date.year, :end\_year  
=\> @program.end\_date.year + 1, :order =\> [:month, :day, :year] %\> |   
\<% if @pgm\_update.pgm\_visits.size \> 1 -%\>  
\<%= link\_to\_remote ‘remove’,  
:update =\> ‘visits’,  
:url =\> {:action =\> :ajax\_remove\_visit, :id =\>  
index },  
:with =\> “Form.serialize(‘application\_form’)”  
%\>  
\<% end -%\>  
 |

  
  
\<% end -%\>  
\<% else -%\>
# 

click ‘+’ to add a visit

  
\<% end -%\>
# each visit instance variable (pgm\_visit1…i) is dynamically generated and set in the action with the following:

# @pgm\_update.pgm\_visits.each\_index do |i| visit = i+1 instance\_variable\_set("@pgm\_visit#{visit}".to\_sym, @pgm\_update.pgm\_visits[i]) end if request.post? @pgm\_update.pgm\_visits.each\_index do |i| visit = i+1 instance\_variable\_get("@pgm\_visit# {visit}".to\_sym).attributes = params[“pgm\_visit#{visit}”] end end

I can give more details on request

-John

–  
John S.  
Computing Staff - Webmaster  
Kavli Institute for Theoretical Physics  
University of California, Santa Barbara  
removed\_email\_address@domain.invalid  
(805) 893-6307

---

<div class="post-metadata">

**Author:** ![g0nzo](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/g/3bc359/32.png) [@g0nzo](https://www.ruby-forum.com/u/g0nzo)\
**Post date:** [March 28, 2006, 11:58pm UTC](https://www.ruby-forum.com/t/has-many-and-belongs-to-example/76622/6 "2006-03-28T23:58:04Z")

</div>

These examples have helped me a lot!

My problem is this, how do you UPDATE child records? Every tutorial  
and book I see only addresses the parent/child saving issue in the New  
method.

I can’t do a find for children, because I don’t know the child.id and  
each parent will have at least 3 children.

John S. wrote:

> # I believe you are doing the same thing I had to do for a person having multiple visits for a given program. I am using AJAX links to add and remove visits. My form looked like this…
> 
> \<% unless @pgm\_update.pgm\_visits.empty? -%\>  
> \<% @pgm\_update.pgm\_visits.each\_index do |index| %\>
> 
>   
>   
>   
>   
>   
>   
>   
> 
> | \<%= plus\_one(index) %\>. &nbsp; | Start:   
>   
> End: | \<%= date\_select “pgm\_visit#{plus\_one  
> (index)}”,“start”, :start\_year =\> @program.start\_date.year, :end\_year  
> =\> @program.end\_date.year + 1, :order =\> [:month, :day, :year] %\>  
>   
> \<%= date\_select “pgm\_visit#{plus\_one  
> (index)}”,“ends”, :start\_year =\> @program.start\_date.year, :end\_year  
> =\> @program.end\_date.year + 1, :order =\> [:month, :day, :year] %\> |   
> \<% if @pgm\_update.pgm\_visits.size \> 1 -%\>  
> \<%= link\_to\_remote ‘remove’,  
> :update =\> ‘visits’,  
> :url =\> {:action =\> :ajax\_remove\_visit, :id =\>  
> index },  
> :with =\> “Form.serialize(‘application\_form’)”  
> %\>  
> \<% end -%\>  
> |
> 
>   
>   
> \<% end -%\>  
> \<% else -%\>
> # 
> 
> click ‘+’ to add a visit
> 
>   
> \<% end -%\>
> # each visit instance variable (pgm\_visit1…i) is dynamically generated and set in the action with the following:
> 
> # @pgm\_update.pgm\_visits.each\_index do |i| visit = i+1 instance\_variable\_set("@pgm\_visit#{visit}".to\_sym, @pgm\_update.pgm\_visits[i]) end if request.post? @pgm\_update.pgm\_visits.each\_index do |i| visit = i+1 instance\_variable\_get("@pgm\_visit# {visit}".to\_sym).attributes = params[“pgm\_visit#{visit}”] end end
> 
> I can give more details on request
> 
> -John
> 
> –  
> John S.  
> Computing Staff - Webmaster  
> Kavli Institute for Theoretical Physics  
> University of California, Santa Barbara  
> removed\_email\_address@domain.invalid  
> (805) 893-6307
