SlideShare una empresa de Scribd logo
1 de 13
Descargar para leer sin conexión
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.

Más contenido relacionado

La actualidad más candente

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
 

La actualidad más candente (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 a 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 a 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
 

Último

Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...
Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...
Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...amilabibi1
 
Bladex 1Q24 Earning Results Presentation
Bladex 1Q24 Earning Results PresentationBladex 1Q24 Earning Results Presentation
Bladex 1Q24 Earning Results PresentationBladex
 
fca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdffca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdfHenry Tapper
 
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
 
Governor Olli Rehn: Dialling back monetary restraint
Governor Olli Rehn: Dialling back monetary restraintGovernor Olli Rehn: Dialling back monetary restraint
Governor Olli Rehn: Dialling back monetary restraintSuomen Pankki
 
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
 
Financial Leverage Definition, Advantages, and Disadvantages
Financial Leverage Definition, Advantages, and DisadvantagesFinancial Leverage Definition, Advantages, and Disadvantages
Financial Leverage Definition, Advantages, and Disadvantagesjayjaymabutot13
 
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...Amil Baba Dawood bangali
 
PMFBY , Pradhan Mantri Fasal bima yojna
PMFBY , Pradhan Mantri  Fasal bima yojnaPMFBY , Pradhan Mantri  Fasal bima yojna
PMFBY , Pradhan Mantri Fasal bima yojnaDharmendra Kumar
 
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
 
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证jdkhjh
 
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》rnrncn29
 
Current Economic situation of Pakistan .pptx
Current Economic situation of Pakistan .pptxCurrent Economic situation of Pakistan .pptx
Current Economic situation of Pakistan .pptxuzma244191
 
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170Sonam Pathan
 
government_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfgovernment_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfshaunmashale756
 
212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technologyz xss
 
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...Amil baba
 
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfmagnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfHenry Tapper
 
2024 Q1 Crypto Industry Report | CoinGecko
2024 Q1 Crypto Industry Report | CoinGecko2024 Q1 Crypto Industry Report | CoinGecko
2024 Q1 Crypto Industry Report | CoinGeckoCoinGecko
 

Último (20)

Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...
Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...
Amil Baba In Pakistan amil baba in Lahore amil baba in Islamabad amil baba in...
 
Bladex 1Q24 Earning Results Presentation
Bladex 1Q24 Earning Results PresentationBladex 1Q24 Earning Results Presentation
Bladex 1Q24 Earning Results Presentation
 
fca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdffca-bsps-decision-letter-redacted (1).pdf
fca-bsps-decision-letter-redacted (1).pdf
 
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
 
Governor Olli Rehn: Dialling back monetary restraint
Governor Olli Rehn: Dialling back monetary restraintGovernor Olli Rehn: Dialling back monetary restraint
Governor Olli Rehn: Dialling back monetary restraint
 
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
 
Financial Leverage Definition, Advantages, and Disadvantages
Financial Leverage Definition, Advantages, and DisadvantagesFinancial Leverage Definition, Advantages, and Disadvantages
Financial Leverage Definition, Advantages, and Disadvantages
 
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...
NO1 WorldWide online istikhara for love marriage vashikaran specialist love p...
 
PMFBY , Pradhan Mantri Fasal bima yojna
PMFBY , Pradhan Mantri  Fasal bima yojnaPMFBY , Pradhan Mantri  Fasal bima yojna
PMFBY , Pradhan Mantri Fasal bima yojna
 
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 🔝✔️✔️
 
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
原版1:1复刻堪萨斯大学毕业证KU毕业证留信学历认证
 
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
《加拿大本地办假证-寻找办理Dalhousie毕业证和达尔豪斯大学毕业证书的中介代理》
 
Current Economic situation of Pakistan .pptx
Current Economic situation of Pakistan .pptxCurrent Economic situation of Pakistan .pptx
Current Economic situation of Pakistan .pptx
 
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170
Call Girls Near Golden Tulip Essential Hotel, New Delhi 9873777170
 
government_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdfgovernment_intervention_in_business_ownership[1].pdf
government_intervention_in_business_ownership[1].pdf
 
🔝+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
 
212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology212MTAMount Durham University Bachelor's Diploma in Technology
212MTAMount Durham University Bachelor's Diploma in Technology
 
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...
NO1 WorldWide Genuine vashikaran specialist Vashikaran baba near Lahore Vashi...
 
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdfmagnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
magnetic-pensions-a-new-blueprint-for-the-dc-landscape.pdf
 
2024 Q1 Crypto Industry Report | CoinGecko
2024 Q1 Crypto Industry Report | CoinGecko2024 Q1 Crypto Industry Report | CoinGecko
2024 Q1 Crypto Industry Report | CoinGecko
 

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.