How to get the name of foreign_key column
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.
精彩评论