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="checked"<%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("You must specify a tag")
       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 (10)

Android practice of layout in application-chapter6
Android practice of layout in application-chapter6Android practice of layout in application-chapter6
Android practice of layout in application-chapter6
 
Introduction to oracle functions
Introduction to oracle functionsIntroduction to oracle functions
Introduction to oracle functions
 
Les06
Les06Les06
Les06
 
Lab4 join - all types listed
Lab4   join - all types listedLab4   join - all types listed
Lab4 join - all types listed
 
Devry bis-155-i lab-6
Devry bis-155-i lab-6Devry bis-155-i lab-6
Devry bis-155-i lab-6
 
70 562
70 56270 562
70 562
 
Les17
Les17Les17
Les17
 
Excel 2007 Unit K
Excel 2007 Unit KExcel 2007 Unit K
Excel 2007 Unit K
 
Les18
Les18Les18
Les18
 
Sql task
Sql taskSql task
Sql task
 

Viewers also liked

Case Solution for Hutchison Whampoa Ltd.: The Capital Structure Decision
Case Solution for Hutchison Whampoa Ltd.: The Capital Structure DecisionCase Solution for Hutchison Whampoa Ltd.: The Capital Structure Decision
Case Solution for Hutchison Whampoa Ltd.: The Capital Structure Decisioncasesolutions12
 
28 4 Echinoderms
28 4 Echinoderms28 4 Echinoderms
28 4 EchinodermsTamara
 
Asturias Vistas 14
Asturias Vistas 14Asturias Vistas 14
Asturias Vistas 14Ana Alonso
 
Triumph Over Time Dr Shriniwas Janardan Kashalikar
Triumph Over Time Dr  Shriniwas Janardan KashalikarTriumph Over Time Dr  Shriniwas Janardan Kashalikar
Triumph Over Time Dr Shriniwas Janardan Kashalikarbanothkishan
 
Hampstead Social Programme 22/02/16
Hampstead Social Programme 22/02/16Hampstead Social Programme 22/02/16
Hampstead Social Programme 22/02/16Kat Holloway
 
Walaval Dr Shriniwas Kashalikar
Walaval Dr  Shriniwas KashalikarWalaval Dr  Shriniwas Kashalikar
Walaval Dr Shriniwas Kashalikarbanothkishan
 
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...ProfessorPrincipiante
 
7 面向对象设计原则
7 面向对象设计原则7 面向对象设计原则
7 面向对象设计原则yiditushe
 
NAHB - Opportunity Knocks for Home Buyer\'s
NAHB - Opportunity Knocks for Home Buyer\'sNAHB - Opportunity Knocks for Home Buyer\'s
NAHB - Opportunity Knocks for Home Buyer\'sCarolyn Musselman
 
O ultimo lutador_book_proac_ [456049]
O ultimo lutador_book_proac_ [456049]O ultimo lutador_book_proac_ [456049]
O ultimo lutador_book_proac_ [456049]Cicero Feltrin
 
Case Solution for Diabetogen
Case Solution for DiabetogenCase Solution for Diabetogen
Case Solution for Diabetogencasesolutions12
 

Viewers also liked (18)

Case Solution for Hutchison Whampoa Ltd.: The Capital Structure Decision
Case Solution for Hutchison Whampoa Ltd.: The Capital Structure DecisionCase Solution for Hutchison Whampoa Ltd.: The Capital Structure Decision
Case Solution for Hutchison Whampoa Ltd.: The Capital Structure Decision
 
Pre estomago de los rumiantes
Pre estomago de los rumiantesPre estomago de los rumiantes
Pre estomago de los rumiantes
 
Reporteeeeeeee finaaaaaaaallll
Reporteeeeeeee finaaaaaaaallllReporteeeeeeee finaaaaaaaallll
Reporteeeeeeee finaaaaaaaallll
 
28 4 Echinoderms
28 4 Echinoderms28 4 Echinoderms
28 4 Echinoderms
 
Asturias Vistas 14
Asturias Vistas 14Asturias Vistas 14
Asturias Vistas 14
 
Triumph Over Time Dr Shriniwas Janardan Kashalikar
Triumph Over Time Dr  Shriniwas Janardan KashalikarTriumph Over Time Dr  Shriniwas Janardan Kashalikar
Triumph Over Time Dr Shriniwas Janardan Kashalikar
 
สมมุติฐาน
สมมุติฐานสมมุติฐาน
สมมุติฐาน
 
Hampstead Social Programme 22/02/16
Hampstead Social Programme 22/02/16Hampstead Social Programme 22/02/16
Hampstead Social Programme 22/02/16
 
Walaval Dr Shriniwas Kashalikar
Walaval Dr  Shriniwas KashalikarWalaval Dr  Shriniwas Kashalikar
Walaval Dr Shriniwas Kashalikar
 
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...
A PROBLEMÁTICA DO INÍCIO DA CARREIRA DOCENTE EM MATEMÁTICA: MAPEAMENTO DOS ES...
 
SFUSGS
SFUSGSSFUSGS
SFUSGS
 
7 面向对象设计原则
7 面向对象设计原则7 面向对象设计原则
7 面向对象设计原则
 
CV Luiz Souza
CV Luiz SouzaCV Luiz Souza
CV Luiz Souza
 
NAHB - Opportunity Knocks for Home Buyer\'s
NAHB - Opportunity Knocks for Home Buyer\'sNAHB - Opportunity Knocks for Home Buyer\'s
NAHB - Opportunity Knocks for Home Buyer\'s
 
0302 A New Paradigm for Rice and Why We Think It Works
0302 A New Paradigm for Rice and Why We Think It Works0302 A New Paradigm for Rice and Why We Think It Works
0302 A New Paradigm for Rice and Why We Think It Works
 
Aprendizaje vivencial
Aprendizaje vivencial Aprendizaje vivencial
Aprendizaje vivencial
 
O ultimo lutador_book_proac_ [456049]
O ultimo lutador_book_proac_ [456049]O ultimo lutador_book_proac_ [456049]
O ultimo lutador_book_proac_ [456049]
 
Case Solution for Diabetogen
Case Solution for DiabetogenCase Solution for Diabetogen
Case Solution for Diabetogen
 

Similar to has_many_and_belongs_to_many

Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator projectAmit Sharma
 
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
 
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
 
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
 
What Are the Key Steps in Scraping Product Data from Amazon India.pptx
What Are the Key Steps in Scraping Product Data from Amazon India.pptxWhat Are the Key Steps in Scraping Product Data from Amazon India.pptx
What Are the Key Steps in Scraping Product Data from Amazon India.pptxProductdata Scrape
 
What Are the Key Steps in Scraping Product Data from Amazon India.pdf
What Are the Key Steps in Scraping Product Data from Amazon India.pdfWhat Are the Key Steps in Scraping Product Data from Amazon India.pdf
What Are the Key Steps in Scraping Product Data from Amazon India.pdfProductdata Scrape
 
Database Modeling presentation
Database Modeling  presentationDatabase Modeling  presentation
Database Modeling presentationBhavishya Tyagi
 
.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12aminmesbahi
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewRyan Cross
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2Techglyphs
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republicKaing Menglieng
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence PortfolioChris Seebacher
 
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
 
04 quiz 1 answer key
04 quiz 1 answer key04 quiz 1 answer key
04 quiz 1 answer keyAnne Lee
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfoliomwillmer
 
Develop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfDevelop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfflashfashioncasualwe
 

Similar to has_many_and_belongs_to_many (20)

Oracle data integrator project
Oracle data integrator projectOracle data integrator project
Oracle data integrator project
 
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
 
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...
 
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
 
What Are the Key Steps in Scraping Product Data from Amazon India.pptx
What Are the Key Steps in Scraping Product Data from Amazon India.pptxWhat Are the Key Steps in Scraping Product Data from Amazon India.pptx
What Are the Key Steps in Scraping Product Data from Amazon India.pptx
 
What Are the Key Steps in Scraping Product Data from Amazon India.pdf
What Are the Key Steps in Scraping Product Data from Amazon India.pdfWhat Are the Key Steps in Scraping Product Data from Amazon India.pdf
What Are the Key Steps in Scraping Product Data from Amazon India.pdf
 
Database Modeling presentation
Database Modeling  presentationDatabase Modeling  presentation
Database Modeling presentation
 
.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12.NET Core, ASP.NET Core Course, Session 12
.NET Core, ASP.NET Core Course, Session 12
 
Advanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your ViewAdvanced Drupal Views: Theming your View
Advanced Drupal Views: Theming your View
 
Bt0082 visual basic2
Bt0082 visual basic2Bt0082 visual basic2
Bt0082 visual basic2
 
Catalog display
Catalog displayCatalog display
Catalog display
 
Actionview
ActionviewActionview
Actionview
 
Understand when to use user defined functions in sql server tech-republic
Understand when to use user defined functions in sql server   tech-republicUnderstand when to use user defined functions in sql server   tech-republic
Understand when to use user defined functions in sql server tech-republic
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 
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
 
04 quiz 1 answer key
04 quiz 1 answer key04 quiz 1 answer key
04 quiz 1 answer key
 
Schema webinar
Schema webinarSchema webinar
Schema webinar
 
.NET Portfolio
.NET Portfolio.NET Portfolio
.NET Portfolio
 
Develop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdfDevelop an inventory management system for an electronics store. The .pdf
Develop an inventory management system for an electronics store. The .pdf
 

More from tutorialsruby

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>tutorialsruby
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008tutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheetstutorialsruby
 

More from tutorialsruby (20)

&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
TopStyle Help &amp; &lt;b>Tutorial&lt;/b>
 
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
The Art Institute of Atlanta IMD 210 Fundamentals of Scripting &lt;b>...&lt;/b>
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0Standardization and Knowledge Transfer – INS0
Standardization and Knowledge Transfer – INS0
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml_basics
xhtml_basicsxhtml_basics
xhtml_basics
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
xhtml-documentation
xhtml-documentationxhtml-documentation
xhtml-documentation
 
CSS
CSSCSS
CSS
 
CSS
CSSCSS
CSS
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa0602690047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
0047ecaa6ea3e9ac0a13a2fe96f4de3bfd515c88f5d90c1fae79b956363d7f02c7fa060269
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
HowTo_CSS
HowTo_CSSHowTo_CSS
HowTo_CSS
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
BloggingWithStyle_2008
BloggingWithStyle_2008BloggingWithStyle_2008
BloggingWithStyle_2008
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 
cascadingstylesheets
cascadingstylesheetscascadingstylesheets
cascadingstylesheets
 

Recently uploaded

Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 

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="checked"<%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("You must specify a tag") 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.