Use has_many :through. I'd rename the tables slightly though:
Code:
Reports
=============
id | name
Sections
=============
id | name
listings
==================================
report_id | section_id | user_order
Then your models:
Code:
class Report < ActiveRecord::Base
has_many :listings, :dependent => true
has_many :sections, :through => :listings
end
class Section < ActiveRecord::Base
has_many :listings, :dependent => true
has_many :reports, :through => :listings
end
class Listing < ActiveRecord::Base
belongs_to :report
belongs_to :section
end
Now to show a few examples:
Code:
#create sections and reports
home_section = Section.create(:name => 'home')
work_section = Section.create(:name => 'work')
tps_report = Report.create(:name => 'TPS Report')
#bind report to sections
Listing.create(:report => tps_report, :section => work_section, :user_order => 1)
Listing.create(:report => tps_report, :section => home_section, :user_order => 560)
# Access user order given report and section IDs
report = Report.find(1)
puts report.listings.find_by_section_id(1).user_order
#get a count of how many different sections this report is listed in
puts report.sections.size
Bookmarks