Conventions/Model

All,

I've read about twelve different articles and I've yet to find a consistent solution to my conundrum.

I have a 'people' table and an associated 'person' model object. I have a 'preferences' table and an associated 'preference' model object.

People is as trivial as: id, first_name, last_name. Preferences - also trivial: id, name

Now I need to create a nice join table (with a 'value' attribute)...my question is: do I name it 'people_preferences' or 'person_preferences'. I'm inclined to the latter. The definition is pretty obvious: person_id, preference_id, value.

Next question, assuming we go wtih person_preferences and I generate the rails model: ./script/generate model person_preference, I'm thinking my model associations look something like the following - can someone/anyone validate?

class Person   ...

  has_many :person_preferences, :dependent => :destroy   has_many :preferences, :through => :person_preferences

  ... end

class Preference   ...

  has_many :person_preferences, :dependent => :destroy   has_many :people, :through => :person_preferences

  ... end

class Person_Preference   ...

  belongs_to :person   belongs_to :person

  ... end

Interacting with the model would look like:

@person.person_preferences.each{|pref| puts "#{pref.preference.name}" : #{pref.value}}

Thoughts? Am I crazy? Way off the mark?? TIA for any help!

Hi Cory,

You have data on the "join table" therefore you're better using
has_many :through, because without making the model a full AR model,
you won't be able to access the data on it.

So, this is what I'd do:

table name is people class Person < ActiveRecord::Base has_many :person_preferences has_many :preferences, :through => :person_preferences end

table name is person_preferences, has attributes person_id,
preference_id class PersonPreference < ActiveRecord::Base belongs_to :person belongs_to :preference end

table name is preferences class Preference < ActiveRecord::Base has_many :person_preferences has_many :people, :through => :person_preferences end

This gives you maximum flexibility. Note, however, that the hm=>thr
associations act a little differently than simple has_many or
has_and_belongs_to_many associations . I'd look up the docs for both
if I were you in ActiveRecord::Base in the API, just to referesh your
mind.

If you were going to use a has_and_belongs_to_many with a join table,
I'd name the join table what rails expects, which is alphabetically
ascending ordered plural names. Ie:

cats and dogs would end up being cats_dogs (cats comes before dogs
alphabetically, both are plural)

people and preferences would end up being people_preferences (people
comes before preferences alphabetically and both are plural).

Julian.