rails/rails — Issue #4455: has_many association, primary_key option problem
Author: jannyo
Created: 2012-01-13 15:59:51+00:00
State: open

I have 2 tables `grb_tGPost` and `grb_tGPhoto`

grb_tGPost has primary key column with name `gpost_id`
grb_tGPhoto has primary key column with name `photo_id`

One gpost can have many gphotos. Foreign key column in table grb_tGPhoto has name `gpost_id`

Here are corresponding ruby classes definition:

class Post < ActiveRecord::Base

set_table_name "grb_tGPost"
set_primary_key "gpost_id"

has_many :photos, :foreign_key => 'gpost_id', :primary_key => 'photo_id'

end

class Photo < ActiveRecord::Base

set_table_name "grb_tGPhoto"
set_primary_key "photo_id"

belongs_to :post, :foreign_key => 'gpost_id'

end

The problem is when I run for example this sequence of commands:

my_post = Post.first
my_photos = my_post.photo_ids

Ruby sends these queries to db:

SELECT `grb_tGPost`.* FROM `grb_tGPost` LIMIT 1

SELECT `grb_tGPhoto`.photo_id FROM `grb_tGPhoto` WHERE `grb_tGPhoto.`gpost_id` IS NULL

First query is for this command: "my_post = Post.first". It's ok and I get row with primary key ('gpost_id') = 3848

Second query is for this command: "my_photos = my_post.photo_ids".
It's not ok because of the "`grb_tGPhoto.`gpost_id` IS NULL" at the end.
It should be like this "`grb_tGPhoto.`gpost_id` = 3848"

But in the case when I dont use the option ":primary_key" in association definition, everything works well.
version of my activerecord library: 3.1.3