I know this is an old thread, but as it seems to have the best advice 
I've seen on this subject, I'm going to throw my few cents in here.

I'm strongly leaning in the direction of a shared primary/foreign key 
for situations where the parent record is a prerequisite for the child 
record.  Effectively, the child record is an aspect of the parent 
record.  It could be modeled using a single parent table that is really 
wide (i.e. that contains columns for all of the child records), but 
there may be good reasons not to do that.

The approach I am taking is as follows:
Use the normal Rails :id column for both tables.

It appears in testing against Postgresql that one can have an 
auto-increment primary key and still specify the primary key value when 
creating a new record.  In order to enforce this, I specify `validates 
:id, presence: true, uniqueness: true` in the model for the child table. 
If I run into a database that won't let me specify the value for an 
auto-increment field when creating a new record I'll switch to using 
`id: false` in the migration and manually create the `id` field as an 
integer and then specify a unique index on it.

I specify belongs_to on the child record and pass `foreign_key: :id`.  I 
do the same for specifying has_one on the parent record.

There is no need to specify self.primary_key (the replacement for 
set_primary_key) on the child model since the primary key is still :id.

I'm using a nested singular resource for the child record when routing 
like so:

  resources :user do
    resource :instructor
  end

That sets up routes like so:
  /users/:id
  /users/:user_id/instructor

Because I used :id throughout, when using the route helpers like 
user_instructor_path, I can pass either a User or an Instructor object 
and I will still get the correct route.

I'm still experimenting with this approach, but so far I'm reasonably 
happy with it.

-- 
Posted via http://www.ruby-forum.com/.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to rubyonrails-talk+unsubscr...@googlegroups.com.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
For more options, visit https://groups.google.com/groups/opt_out.


Reply via email to