Set the foreign key constraint column name?


#1

I am applying Rails to an existing schema and not sure how much the
existing developers will let me go in and rename things. So I need to
discover the limits of what I can change with Rails.

I’ve found set_table_name and set_primary_key, which have been very
useful.

If I have a “foo has_one :bar” relationship, but then in the bar table
my column is named “fooid” or some other thing that is not “foo_id”, is
there a similar helper command I can use to change it? Everything’s
working swimmingly for me, except when I get to this bit and it errors
out telling me “cannot find bar.foo_id” and I can’t figure out a way to
point to bar.fooid and say “There it is.”

I tried googling around for “set foreign key constraint column name” but
can’t seem to track anything down.

Thanks!


#2

Duane wrote:

I am applying Rails to an existing schema and not sure how much the
existing developers will let me go in and rename things. So I need to
discover the limits of what I can change with Rails.

I’ve found set_table_name and set_primary_key, which have been very
useful.

If I have a “foo has_one :bar” relationship, but then in the bar table
my column is named “fooid” or some other thing that is not “foo_id”, is
there a similar helper command I can use to change it? Everything’s
working swimmingly for me, except when I get to this bit and it errors
out telling me “cannot find bar.foo_id” and I can’t figure out a way to
point to bar.fooid and say “There it is.”

I tried googling around for “set foreign key constraint column name” but
can’t seem to track anything down.

Thanks!

Look for the docs for has_one
There is a :foreign_key option there

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000472


#3

Hi, Duane,

the relationships (for example has_many) take options. One of these
options is foreign_key. See
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000471
for example.

Regards
Jan


#4

foo has_one :bar, :foreign_key => “fooid”


#5

Jan P. wrote:

Hi, Duane,

the relationships (for example has_many) take options. One of these
options is foreign_key. See
http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000471
for example.

Regards
Jan

Thanks everybody, sorry for the RTFM. I was going through “Agile Web
Development with Rails” and glanced right over it because that option
was discussed as part of belongs_to, not has_to. That’s what I get for
speedskimming.

I knew it had to be an easy answer :).

d