【问题标题】:For an ActiveRecord one-to-many association, which :foreign_key option should I set?对于 ActiveRecord 一对多关联,我应该设置哪个 :foreign_key 选项?
【发布时间】:2009-05-13 21:48:22
【问题描述】:

ActiveRecord 的has_manybelongs_to 方法都采用:foreign_key 选项。如果我需要使用它来处理非标准的 FK 列名,我应该为父模型(has_many)、子模型(belongs_to)还是两者都设置它,还是有关系?

【问题讨论】:

    标签: ruby-on-rails ruby activerecord


    【解决方案1】:

    您应该同时设置:foreign_key 选项。

    考虑以下两种模型:

    class Article < ActiveRecord::Base
      has_many :comments, :foreign_key => "articleID"
    end
    
    class Comment < ActiveRecord::Base
      belongs_to :article, :foreign_key => "articleID"
    end
    

    Article 类中声明has_many 允许您执行以下操作:

    Article.find(12).comments  # Finds all comments with comment.articleID == 12
    

    Comment 模型中的 belongs_to 方法调用允许:

    Comment.last.article       # Finds article with article.id == comment.articleID
    

    如您所见,在这两种情况下都使用了外键。如果在任一位置省略,该特定关联代理将无法正常工作。

    【讨论】:

    • 您不必总是需要同时设置:foreign_key 选项。在您的特定示例中,您这样做了,因为您有一个旧的列名。然而,当你只是重命名一个关联时,这个问题会出现很多,即belongs_to :default_account, :class_name =&gt; "Account", :foreign_key =&gt; "account_id"。 Account类中对应的has_one不需要指定外键。
    【解决方案2】:

    belongs_to 猜测外键是关联名称加上_id

    has_one 猜测外键是包含类的名称加上_id

    通常对于非标准密钥,您只需要在一个地方。

    class Book < ActiveRecord::Base
      # Rails default fk is isbn_id
      belongs_to :isbn, :class_name => "BarCode", :foreign_key => "bar_code_id" 
    end
    
    class BarCode < ActiveRecord::Base
      # Rails default fk is bar_code_id, so you don't need to specify it
      has_one :book
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多