-
ActiveRecord
Hi everyone
At the moment I have been stuck with making a form (with categories) using info from a single table called bases.
In it are the columns 'category', 'use', 'location' (or at least these are the important ones)
Non of these columns are unique so for example I may have:
8 'Boating' entries (based on category)
these 8 'Boating' entries are split by `use` into 'Inshore', 'Coastal' or 'Offshore'
of which each may/does have separate locations for example 'river', 'gulf', 'harbour' etc etc etc
so in table form
|category| |use| |location| |other data I actually need|
Boating Inshore river blah
Boating Inshore gulf blah
Boating Inshore harbour' blah
Boating Coastal harbour' blah
Boating Coastal gulf blah
So as I mention I have to be able to categories this form so that a user selects a
category to get the use options and then select a use to get the location options
Now for what im trying to do is create a ActiveRecord object BaseDraft that belongs_to :base in 3 different ways but the code below doesn't seem to be working.
Code:
Object BaseDraft < ActiveRecord::Base
belongs_to :category, :class_name => 'Base', :foriegn_key => 'category_id'
belongs_to :use, :class_name => 'Base', :foriegn_key => 'use_id'
belongs_to :location, :class_name => 'Base', :foriegn_key => 'location_id'
end
My motivation for this is so within the form partials I only have a single point of reference to retreive all the information needed by each select (including the currently selected option).
How would I do this? or is this hopeless and I should just do this a more "manual" way?
-
You have to create separate tables if you want to use associations:
basedrafts: id, category_id, ....
categories: id, name
then:
Code:
class BaseDraft < ActiveRecord::Base
belongs_to :category
end
You can now use:
Code:
@a_base = BaseDraft.find(3) # SELECT * FROM base_drafts WHERE id=3
@a_base.category # selects category of this basedraft
-
Thanks
Ive come up with a bit of a hack for this. Essentually I created some wrapping methods for the Draft class so they implement multiple functionality on one relationship. It's not pretty but its working and its not as ugly as I could have done it :)