我正在使用 Rails 3,我有一个简单的模型
class Post
has_many :comments
end
我正在做一些元编程,我需要知道注释表中的 foreign_key 的名称。
在上面的例子中答案是
post_id
然而,它可以是任何东西,因为用户可以进行配置。
假设您可以访问 Post 和 Comment 这两个类,您将如何获得 foreign_key 的名称?
更新:经过一些测试后,这就是我得到的。
> User.reflections[:phone_numbers].instance_variable_get('@primary_key_name')
=> "user_id"
以上解决方案适用于
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 ?
试试这个:
. rails console
Loading development environment (Rails 3.0.9)
irb(main):001:0> "Post".foreign_key
=> "post_id"
这是完整的 Documentation .请让我知道这对你有没有用。我还没有在自定义外键上尝试过这个。希望这会有所帮助。
关于ruby-on-rails - 如何获取 foreign_key 列的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6541794/