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
 
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
 
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
 

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
 
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
 
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
 

Último

The Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfThe Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfGale Pooley
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceanilsa9823
 
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130Suhani Kapoor
 
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...ssifa0344
 
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Call Girls in Nagpur High Profile
 
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...ssifa0344
 
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Pooja Nehwal
 
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Delhi Call girls
 
The Economic History of the U.S. Lecture 22.pdf
The Economic History of the U.S. Lecture 22.pdfThe Economic History of the U.S. Lecture 22.pdf
The Economic History of the U.S. Lecture 22.pdfGale Pooley
 
Booking open Available Pune Call Girls Shivane 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Shivane  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Shivane  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Shivane 6297143586 Call Hot Indian Gi...Call Girls in Nagpur High Profile
 
Dividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxDividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxanshikagoel52
 
20240429 Calibre April 2024 Investor Presentation.pdf
20240429 Calibre April 2024 Investor Presentation.pdf20240429 Calibre April 2024 Investor Presentation.pdf
20240429 Calibre April 2024 Investor Presentation.pdfAdnet Communications
 
03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptxFinTech Belgium
 
Booking open Available Pune Call Girls Wadgaon Sheri 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Wadgaon Sheri  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Wadgaon Sheri  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Wadgaon Sheri 6297143586 Call Hot Ind...Call Girls in Nagpur High Profile
 
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdfFinTech Belgium
 
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfGale Pooley
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designsegoetzinger
 
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home DeliveryPooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home DeliveryPooja Nehwal
 

Último (20)

The Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdfThe Economic History of the U.S. Lecture 30.pdf
The Economic History of the U.S. Lecture 30.pdf
 
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual serviceCALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
CALL ON ➥8923113531 🔝Call Girls Gomti Nagar Lucknow best sexual service
 
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
VIP Call Girls Service Dilsukhnagar Hyderabad Call +91-8250192130
 
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...
Solution Manual for Financial Accounting, 11th Edition by Robert Libby, Patri...
 
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...Top Rated  Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
Top Rated Pune Call Girls Viman Nagar ⟟ 6297143586 ⟟ Call Me For Genuine Sex...
 
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
TEST BANK For Corporate Finance, 13th Edition By Stephen Ross, Randolph Weste...
 
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
(INDIRA) Call Girl Mumbai Call Now 8250077686 Mumbai Escorts 24x7
 
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
Vip Call US 📞 7738631006 ✅Call Girls In Sakinaka ( Mumbai )
 
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
Best VIP Call Girls Noida Sector 18 Call Me: 8448380779
 
The Economic History of the U.S. Lecture 22.pdf
The Economic History of the U.S. Lecture 22.pdfThe Economic History of the U.S. Lecture 22.pdf
The Economic History of the U.S. Lecture 22.pdf
 
Booking open Available Pune Call Girls Shivane 6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Shivane  6297143586 Call Hot Indian Gi...Booking open Available Pune Call Girls Shivane  6297143586 Call Hot Indian Gi...
Booking open Available Pune Call Girls Shivane 6297143586 Call Hot Indian Gi...
 
Dividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptxDividend Policy and Dividend Decision Theories.pptx
Dividend Policy and Dividend Decision Theories.pptx
 
20240429 Calibre April 2024 Investor Presentation.pdf
20240429 Calibre April 2024 Investor Presentation.pdf20240429 Calibre April 2024 Investor Presentation.pdf
20240429 Calibre April 2024 Investor Presentation.pdf
 
03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx03_Emmanuel Ndiaye_Degroof Petercam.pptx
03_Emmanuel Ndiaye_Degroof Petercam.pptx
 
Booking open Available Pune Call Girls Wadgaon Sheri 6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Wadgaon Sheri  6297143586 Call Hot Ind...Booking open Available Pune Call Girls Wadgaon Sheri  6297143586 Call Hot Ind...
Booking open Available Pune Call Girls Wadgaon Sheri 6297143586 Call Hot Ind...
 
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf
06_Joeri Van Speybroek_Dell_MeetupDora&Cybersecurity.pdf
 
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Koregaon Park Call Me 7737669865 Budget Friendly No Advance Booking
 
The Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdfThe Economic History of the U.S. Lecture 17.pdf
The Economic History of the U.S. Lecture 17.pdf
 
Instant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School DesignsInstant Issue Debit Cards - School Designs
Instant Issue Debit Cards - School Designs
 
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home DeliveryPooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
Pooja 9892124323 : Call Girl in Juhu Escorts Service Free Home Delivery
 

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.