代码之家  ›  专栏  ›  技术社区  ›  Ethan

对于ActiveRecord一对多关联,我应该设置哪个:外键选项?

  •  1
  • Ethan  · 技术社区  · 15 年前

    ActiveRecord的 has_many belongs_to 两种方法都采用了 :foreign_key 选项如果我需要使用它来处理非标准的FK列名,我应该为父模型设置它吗( 你有很多 ),儿童模型( 属于

    2 回复  |  直到 15 年前
        1
  •  2
  •   molf    15 年前

    你应该设置 :foreign_key

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

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

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

    belongs_to 方法调用 Comment 模型允许:

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

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

        2
  •  2
  •   Sarah Mei    15 年前

    belongs_to _id

    has_one 猜测外键是包含类加号的名称 _身份证

    通常对于非标准密钥,您只需要在一个位置使用它。

    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