Ruby on Rails的引导文件放在ActiveRecord的关联不正确的? [英] Ruby on Rails guides document on Activerecord association incorrect?

查看:114
本文介绍了Ruby on Rails的引导文件放在ActiveRecord的关联不正确的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

哇,我一直在努力奋斗着这个一整天,下面就以官方红宝石导轨导向的文件,才发现,原来我可能会被误导了文档中的所有沿。我只是想确认这是否属实。

Wow I've been struggling with this for whole day, following the "official" ruby on rails guides document, and just discovered that I might have been misguided by the document all along. I just want to confirm if this is true.

如果你去 http://guides.rubyonrails.org/association_basics.html 并在2.10。自加入部分,它说:

If you go to http://guides.rubyonrails.org/association_basics.html and under 2.10. self joins section it says:

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee"
  belongs_to :manager, :class_name => "Employee",
    :foreign_key => "manager_id"
end

现在,我是一个新手,刚认为,在这个code(我还能做什么?),并写了一些code这就是这种自我的变化加入的情况下。然而,更多的我看着它越感觉不对。是不是:下属应该有:foreign_key 字段,而不是:经理?反正我只是改变了它,使得code是这样的:

Now, I'm a newbie and just believed in this code (What else can I do?) and wrote some code that's a variation of this self join case. However the more I looked at it the more it didn't feel right. isn't :subordinates supposed to have the :foreign_key field instead of :manager? Anyway I've just changed it so that the code is something like:

class Employee < ActiveRecord::Base
  has_many :subordinates, :class_name => "Employee", :foreign_key => "manager_id"
  belongs_to :manager, :class_name => "Employee"
end

和现在的工作。我失去了一些东西?或者是正式文件错了吗?很难相信,正式文件将present不正确的信息,但也许这就是事情是这样的。

and now it's working. Am I missing something? Or is the official document wrong? It's hard to believe that the official document would present incorrect information but maybe that's the way it is.

推荐答案

这是正确的,的指导性文件是不正确在写这篇文章的时候。

That's right, the guide document is incorrect at the time of this writing.

belongs_to的不需要:foreign_key 选项,因为AR会推断 MANAGER_ID 从协会(经理)的名称。作为记录,AR会产生错误的时候,给予员工 @dwight 人们试图 @ dwight.subordinates ,因为AR将使用 EMPLOYEE_ID SELECT语句的WHERE条件。

The belongs_to doesn't need the :foreign_key option because AR will infer manager_id from the name of the association ("manager"). As documented, AR would raise an error when, given an Employee @dwight one attempts to @dwight.subordinates, because AR would use employee_id in the WHERE condition of the SELECT statement.

根据<一href="http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#method-i-has_many"相对=nofollow> AR文档通过了:foreign_key 选项的has_many 结果宣布FK生成的查询 @ dwight.subordinates时将使用

According to the AR documentation passing the :foreign_key option to has_many results in declaring the FK that will be used when generating the query for @dwight.subordinates.

这篇关于Ruby on Rails的引导文件放在ActiveRecord的关联不正确的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆