SlideShare a Scribd company logo
1 of 13
Download to read offline
A Many-to-Many tutorial for Rails
                                                 th
                                      September 4 , 2005

                         Creative Commons: Attribution-ShareAlike 2.5
                         Originally by Jeffrey Hicks @ http://jrhicks.net



Introduction
This brief tutorial is a start-to-finish example of the Model, View, and Controller required
for a many-to-many relationship.

This is a follow-along tutorial for a finance application so go ahead and create your rails
app, configure your database.yml, and start your server.
I. Model
Our example application will model financial expenses and tags. To work with rail’s
default expectations we follow a strict naming convention for the database table names
and fields.




Notice the required naming conventions.

   •   expenses is the plural form of expense
   •   tags is the plural form of tag
   •   both primary fields use the lowercase id
   •   the relating table is in alphabetical order expenses_tags
   •   the field relating to a tag’s id is tag_id
   •   the field relating to an expense’s id is expense_id

Create your database using the following schema.


       CREATE TABLE `expenses` (
         `id` int(11) NOT NULL auto_increment,
         `amount` float NOT NULL default '0',
         PRIMARY KEY (`id`)
       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

       CREATE TABLE `tags` (
         `id` int(11) NOT NULL auto_increment,
         `name` varchar(100) NOT NULL default '',
         PRIMARY KEY (`id`)
       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;

       CREATE TABLE `expenses_tags` (
         `expense_id` int(11) NOT NULL default '0',
         `tag_id` int(11) NOT NULL default '0'
       ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Generate your Scaffold for the expense and tag models.




Edit expense.rb to tell your expense model that it has_and_belongs_to_many
:tags
2. View
To allow our web visitors to relate an expense with many tags, we are going to
use multiple checkboxes. This is how it will look.




Our form will generate dynamically from the tags in the database. Execute the
following SQL to populate our example database.


      Insert into tags(name) values ('food');
      Insert into tags(name) values ('restaurant');
      Insert into tags(name) values ('lodging');
Our view should depend on the expenses_controller to load the tags. Add the
@tags=Tag.find_all line to both the new and edit methods as depicted in line 17
& 32 below.
Now we will actually customize our edit and new views. We can do this in one
location; edit your expenses_form.rhtml to include lines 7 through 13.
The tags of existing expenses should be checked when we edit. To enable this
we add the following if statement to line 12.

      <%if @expense.tags.include? tag%>checked=quot;checkedquot;<%end%>
We will also edit the list view, so that we will be able to view our tags. Add the
code on lines 8 and 17-19 to your list.rhtml
3. Controller
The expense_controller’s update and create method receive the requests from the edit
and new view. To store the relationship we need to convert the tag_ids to actual Tag
objects with Tag.find(@params[:tag_ids]) if @params[:tag_ids].

The if @params[:tag_ids] prevents a nil object error when the user doesn’t select
any tag.

Add the lines 22 & 38 to expenses_controller.rb
Optionally
If you intention was to force the user to select a tag, I’ve been told to add this to
the expense model. (expense_controller.rb)

def validate
       if tags.blank?
               errors.add_to_base(quot;You must specify a tagquot;)
       end
end
Conclusion
Add an expense with multiple tags.




View the stored tags after you hit the Create button.
Edit the new expense to see stored tags as checked.




Check out the database entries in the expenses_tags table.
Thanks
August 9, 2005 - Sheldon Hearn noticed a transactional condition with the database.
Where @expense.tags.clear and @expense.tags<<Tag.find(params[:tag_ids]) should
be replaced with a single @expense.tags=Tag.find(params[:tag_ids])

August 9, 2005 – Ecow pointed out multiple documentation errors where I failed to
provide the tags table schema, missing code for assigning attributes on expense
creation, and multiple incorrect references to view and controller methods.

August 11, 2005 – Spiralis pointed out that when editing existing tags … the existing
tags should be checked.

August 17, 2005 – Brian NG suggested a fix for allowing existing tags to be checked.

August 25 – Brandt proposed a solution to the nil object error received when the user
doesn’t select a tag.

More Related Content

What's hot

Devry bis-155-i lab-6
Devry bis-155-i lab-6Devry bis-155-i lab-6
Devry bis-155-i lab-6shyaminfo104
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)Huda Alameen
 
Basic Operation in Excel and Eviews
Basic Operation in Excel and EviewsBasic Operation in Excel and Eviews
Basic Operation in Excel and EviewsSuniya Sheikh
 
Reporting aggregated data using the group functions
Reporting aggregated data using the group functionsReporting aggregated data using the group functions
Reporting aggregated data using the group functionsSyed Zaid Irshad
 
Mobile Programming - 4 Modifiers and Image Card
Mobile Programming - 4 Modifiers and Image CardMobile Programming - 4 Modifiers and Image Card
Mobile Programming - 4 Modifiers and Image CardAndiNurkholis1
 
Write a simple pl
Write a simple plWrite a simple pl
Write a simple plonlytej
 
Regular expressions tutorial for SEO & Website Analysis
Regular expressions tutorial for SEO & Website AnalysisRegular expressions tutorial for SEO & Website Analysis
Regular expressions tutorial for SEO & Website AnalysisGlobal Media Insight
 

What's hot (8)

Devry bis-155-i lab-6
Devry bis-155-i lab-6Devry bis-155-i lab-6
Devry bis-155-i lab-6
 
Excel 2007 Unit K
Excel 2007 Unit KExcel 2007 Unit K
Excel 2007 Unit K
 
Structured query language(sql)
Structured query language(sql)Structured query language(sql)
Structured query language(sql)
 
Basic Operation in Excel and Eviews
Basic Operation in Excel and EviewsBasic Operation in Excel and Eviews
Basic Operation in Excel and Eviews
 
Reporting aggregated data using the group functions
Reporting aggregated data using the group functionsReporting aggregated data using the group functions
Reporting aggregated data using the group functions
 
Mobile Programming - 4 Modifiers and Image Card
Mobile Programming - 4 Modifiers and Image CardMobile Programming - 4 Modifiers and Image Card
Mobile Programming - 4 Modifiers and Image Card
 
Write a simple pl
Write a simple plWrite a simple pl
Write a simple pl
 
Regular expressions tutorial for SEO & Website Analysis
Regular expressions tutorial for SEO & Website AnalysisRegular expressions tutorial for SEO & Website Analysis
Regular expressions tutorial for SEO & Website Analysis
 

Similar to Has Many And Belongs To Many

has_many_and_belongs_to_many
has_many_and_belongs_to_manyhas_many_and_belongs_to_many
has_many_and_belongs_to_manytutorialsruby
 
has_many_and_belongs_to_many
has_many_and_belongs_to_manyhas_many_and_belongs_to_many
has_many_and_belongs_to_manytutorialsruby
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationRandy Connolly
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewRyan Cross
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator projectAmit Sharma
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsTawnaDelatorrejs
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...Julian Hyde
 
Database Modeling presentation
Database Modeling  presentationDatabase Modeling  presentation
Database Modeling presentationBhavishya Tyagi
 
How to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in RHow to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in RPaul Bradshaw
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfmallik3000
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007paulguerin
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2Techglyphs
 
Plsql task
Plsql taskPlsql task
Plsql taskNawaz Sk
 
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeDeveloping Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeSusanMorant
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersBRIJESH KUMAR
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 

Similar to Has Many And Belongs To Many (20)

has_many_and_belongs_to_many
has_many_and_belongs_to_manyhas_many_and_belongs_to_many
has_many_and_belongs_to_many
 
has_many_and_belongs_to_many
has_many_and_belongs_to_manyhas_many_and_belongs_to_many
has_many_and_belongs_to_many
 
ASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And RepresentationASP.NET 08 - Data Binding And Representation
ASP.NET 08 - Data Binding And Representation
 
Ejb4
Ejb4Ejb4
Ejb4
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your View
 
Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator project
 
C++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment InstructionsC++ Programming Class Creation Program Assignment Instructions
C++ Programming Class Creation Program Assignment Instructions
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
Smarter Together - Bringing Relational Algebra, Powered by Apache Calcite, in...
 
Catalog display
Catalog displayCatalog display
Catalog display
 
Database Modeling presentation
Database Modeling  presentationDatabase Modeling  presentation
Database Modeling presentation
 
How to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in RHow to generate a 100+ page website using parameterisation in R
How to generate a 100+ page website using parameterisation in R
 
I am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdfI am having trouble writing the individual files for part 1, which i.pdf
I am having trouble writing the individual files for part 1, which i.pdf
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2
 
Plsql task
Plsql taskPlsql task
Plsql task
 
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass GuaranteeDeveloping Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
Developing Microsoft SQL Server 2012 Databases 70-464 Pass Guarantee
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for DevelopersSQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 

Recently uploaded

letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...
letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...
letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...Henry Tapper
 
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...ranjana rawat
 
SBP-Market-Operations and market managment
SBP-Market-Operations and market managmentSBP-Market-Operations and market managment
SBP-Market-Operations and market managmentfactical
 
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️9953056974 Low Rate Call Girls In Saket, Delhi NCR
 
Chapter 2.ppt of macroeconomics by mankiw 9th edition
Chapter 2.ppt of macroeconomics by mankiw 9th editionChapter 2.ppt of macroeconomics by mankiw 9th edition
Chapter 2.ppt of macroeconomics by mankiw 9th editionMuhammadHusnain82237
 
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptx
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptxOAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptx
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptxhiddenlevers
 
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...First NO1 World Amil baba in Faisalabad
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designsegoetzinger
 
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...yordanosyohannes2
 
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...makika9823
 
Andheri Call Girls In 9825968104 Mumbai Hot Models
Andheri Call Girls In 9825968104 Mumbai Hot ModelsAndheri Call Girls In 9825968104 Mumbai Hot Models
Andheri Call Girls In 9825968104 Mumbai Hot Modelshematsharma006
 
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一(办理学位证)加拿大萨省大学毕业证成绩单原版一比一
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一S SDS
 
Stock Market Brief Deck for 4/24/24 .pdf
Stock Market Brief Deck for 4/24/24 .pdfStock Market Brief Deck for 4/24/24 .pdf
Stock Market Brief Deck for 4/24/24 .pdfMichael Silva
 
Quantitative Analysis of Retail Sector Companies
Quantitative Analysis of Retail Sector CompaniesQuantitative Analysis of Retail Sector Companies
Quantitative Analysis of Retail Sector Companiesprashantbhati354
 
House of Commons ; CDC schemes overview document
House of Commons ; CDC schemes overview documentHouse of Commons ; CDC schemes overview document
House of Commons ; CDC schemes overview documentHenry Tapper
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex
 
Q3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesQ3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesMarketing847413
 

Recently uploaded (20)

🔝9953056974 🔝Call Girls In Dwarka Escort Service Delhi NCR
🔝9953056974 🔝Call Girls In Dwarka Escort Service Delhi NCR🔝9953056974 🔝Call Girls In Dwarka Escort Service Delhi NCR
🔝9953056974 🔝Call Girls In Dwarka Escort Service Delhi NCR
 
letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...
letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...
letter-from-the-chair-to-the-fca-relating-to-british-steel-pensions-scheme-15...
 
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
(DIYA) Bhumkar Chowk Call Girls Just Call 7001035870 [ Cash on Delivery ] Pun...
 
🔝+919953056974 🔝young Delhi Escort service Pusa Road
🔝+919953056974 🔝young Delhi Escort service Pusa Road🔝+919953056974 🔝young Delhi Escort service Pusa Road
🔝+919953056974 🔝young Delhi Escort service Pusa Road
 
SBP-Market-Operations and market managment
SBP-Market-Operations and market managmentSBP-Market-Operations and market managment
SBP-Market-Operations and market managment
 
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️call girls in  Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
call girls in Nand Nagri (DELHI) 🔝 >༒9953330565🔝 genuine Escort Service 🔝✔️✔️
 
Chapter 2.ppt of macroeconomics by mankiw 9th edition
Chapter 2.ppt of macroeconomics by mankiw 9th editionChapter 2.ppt of macroeconomics by mankiw 9th edition
Chapter 2.ppt of macroeconomics by mankiw 9th edition
 
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptx
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptxOAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptx
OAT_RI_Ep19 WeighingTheRisks_Apr24_TheYellowMetal.pptx
 
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
Authentic No 1 Amil Baba In Pakistan Authentic No 1 Amil Baba In Karachi No 1...
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designs
 
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
AfRESFullPaper22018EmpiricalPerformanceofRealEstateInvestmentTrustsandShareho...
 
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...
Independent Lucknow Call Girls 8923113531WhatsApp Lucknow Call Girls make you...
 
Andheri Call Girls In 9825968104 Mumbai Hot Models
Andheri Call Girls In 9825968104 Mumbai Hot ModelsAndheri Call Girls In 9825968104 Mumbai Hot Models
Andheri Call Girls In 9825968104 Mumbai Hot Models
 
Commercial Bank Economic Capsule - April 2024
Commercial Bank Economic Capsule - April 2024Commercial Bank Economic Capsule - April 2024
Commercial Bank Economic Capsule - April 2024
 
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一(办理学位证)加拿大萨省大学毕业证成绩单原版一比一
(办理学位证)加拿大萨省大学毕业证成绩单原版一比一
 
Stock Market Brief Deck for 4/24/24 .pdf
Stock Market Brief Deck for 4/24/24 .pdfStock Market Brief Deck for 4/24/24 .pdf
Stock Market Brief Deck for 4/24/24 .pdf
 
Quantitative Analysis of Retail Sector Companies
Quantitative Analysis of Retail Sector CompaniesQuantitative Analysis of Retail Sector Companies
Quantitative Analysis of Retail Sector Companies
 
House of Commons ; CDC schemes overview document
House of Commons ; CDC schemes overview documentHouse of Commons ; CDC schemes overview document
House of Commons ; CDC schemes overview document
 
Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024Bladex Earnings Call Presentation 1Q2024
Bladex Earnings Call Presentation 1Q2024
 
Q3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast SlidesQ3 2024 Earnings Conference Call and Webcast Slides
Q3 2024 Earnings Conference Call and Webcast Slides
 

Has Many And Belongs To Many

  • 1. A Many-to-Many tutorial for Rails th September 4 , 2005 Creative Commons: Attribution-ShareAlike 2.5 Originally by Jeffrey Hicks @ http://jrhicks.net Introduction This brief tutorial is a start-to-finish example of the Model, View, and Controller required for a many-to-many relationship. This is a follow-along tutorial for a finance application so go ahead and create your rails app, configure your database.yml, and start your server.
  • 2. I. Model Our example application will model financial expenses and tags. To work with rail’s default expectations we follow a strict naming convention for the database table names and fields. Notice the required naming conventions. • expenses is the plural form of expense • tags is the plural form of tag • both primary fields use the lowercase id • the relating table is in alphabetical order expenses_tags • the field relating to a tag’s id is tag_id • the field relating to an expense’s id is expense_id Create your database using the following schema. CREATE TABLE `expenses` ( `id` int(11) NOT NULL auto_increment, `amount` float NOT NULL default '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `tags` ( `id` int(11) NOT NULL auto_increment, `name` varchar(100) NOT NULL default '', PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; CREATE TABLE `expenses_tags` ( `expense_id` int(11) NOT NULL default '0', `tag_id` int(11) NOT NULL default '0' ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
  • 3. Generate your Scaffold for the expense and tag models. Edit expense.rb to tell your expense model that it has_and_belongs_to_many :tags
  • 4. 2. View To allow our web visitors to relate an expense with many tags, we are going to use multiple checkboxes. This is how it will look. Our form will generate dynamically from the tags in the database. Execute the following SQL to populate our example database. Insert into tags(name) values ('food'); Insert into tags(name) values ('restaurant'); Insert into tags(name) values ('lodging');
  • 5. Our view should depend on the expenses_controller to load the tags. Add the @tags=Tag.find_all line to both the new and edit methods as depicted in line 17 & 32 below.
  • 6. Now we will actually customize our edit and new views. We can do this in one location; edit your expenses_form.rhtml to include lines 7 through 13.
  • 7. The tags of existing expenses should be checked when we edit. To enable this we add the following if statement to line 12. <%if @expense.tags.include? tag%>checked=quot;checkedquot;<%end%>
  • 8. We will also edit the list view, so that we will be able to view our tags. Add the code on lines 8 and 17-19 to your list.rhtml
  • 9. 3. Controller The expense_controller’s update and create method receive the requests from the edit and new view. To store the relationship we need to convert the tag_ids to actual Tag objects with Tag.find(@params[:tag_ids]) if @params[:tag_ids]. The if @params[:tag_ids] prevents a nil object error when the user doesn’t select any tag. Add the lines 22 & 38 to expenses_controller.rb
  • 10. Optionally If you intention was to force the user to select a tag, I’ve been told to add this to the expense model. (expense_controller.rb) def validate if tags.blank? errors.add_to_base(quot;You must specify a tagquot;) end end
  • 11. Conclusion Add an expense with multiple tags. View the stored tags after you hit the Create button.
  • 12. Edit the new expense to see stored tags as checked. Check out the database entries in the expenses_tags table.
  • 13. Thanks August 9, 2005 - Sheldon Hearn noticed a transactional condition with the database. Where @expense.tags.clear and @expense.tags<<Tag.find(params[:tag_ids]) should be replaced with a single @expense.tags=Tag.find(params[:tag_ids]) August 9, 2005 – Ecow pointed out multiple documentation errors where I failed to provide the tags table schema, missing code for assigning attributes on expense creation, and multiple incorrect references to view and controller methods. August 11, 2005 – Spiralis pointed out that when editing existing tags … the existing tags should be checked. August 17, 2005 – Brian NG suggested a fix for allowing existing tags to be checked. August 25 – Brandt proposed a solution to the nil object error received when the user doesn’t select a tag.