开发者

How to get the name of foreign_key column

开发者 https://www.devze.com 2023-03-16 09:16 出处:网络
I am using Rails 3 and I have a simple model class Post has_many :comments end I am doing some meta programming and I need to know the name of the foreign_key in the comments table.

I am using Rails 3 and I have a simple model

class Post
  has_many :comments
end

I am doing some meta programming and I need to know the name of the foreign_key in the comments table.

In the above case the answer is

post_id

However it could be anything since user can do c开发者_Go百科onfigurations.

Assuming that you have access to both classes Post and Comment how would you get the name of the foreign_key ?

Update: After some testing this is what I got.

> User.reflections[:phone_numbers].instance_variable_get('@primary_key_name')
 => "user_id" 

Above solution is for

class User
  has_many :phone_numbers
end


I need to know the name of the foreign_key in the comments table.

how would you get the name of the foreign_key ?

Try this:

. rails console
Loading development environment (Rails 3.0.9)
irb(main):001:0> "Post".foreign_key
=> "post_id"

Here is the complete Documentation. Let me know if it works for you. I haven't tried this on custom foreign key though. Hope this helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号