【问题标题】:ror - include foreign key at both ends of has_many and belongs_to?ror - 在has_many 和belongs_to 的两端包含外键?
【发布时间】:2012-01-24 20:44:10
【问题描述】:

我继承的代码有:

class Graphic < ActiveRecord::Base
  has_many :comments, :foreign_key => 'asset_id',  
  :conditions => 'asset_type_id = 5', 
  :order => 'created_at', :dependent => :destroy

class Comment < ActiveRecord::Base
  belongs_to :graphic, :foreign_key => :asset_id

在我看来 has_many 不应该有foreign_key(我相信它在belongs_to 中被引用)但我不确定,你知道吗?

即应该是

class Graphic < ActiveRecord::Base
  has_many :comments,  
  :conditions => 'asset_type_id = 5', 
  :order => 'created_at', :dependent => :destroy

class Comment < ActiveRecord::Base
  belongs_to :graphic, :foreign_key => :asset_id

【问题讨论】:

    标签: ruby-on-rails ruby activerecord has-many belongs-to


    【解决方案1】:

    我认为您正在尝试做一些已经在 Rails 中烘焙的事情。您应该在这里使用多态关联。

    class Comment
      belongs_to :asset, :polymorphic => true
    end
    
    class Graphic
      has_many :comments, :as => :assets
    end
    

    这样,你需要在两边都声明foreign_key。

    【讨论】:

    • 这也是真的……我只是想回答他的问题哈哈。
    【解决方案2】:

    在 Rails 的 has_many 语句中,:foreign_key 确实是一个选项,在 ActiveRecord documentation 中有此描述:

    指定用于关联的外键。默认情况下,这被猜测为这个类的小写名称和“_id”后缀。因此,建立 has_many 关联的 Person 类将使用“person_id”作为默认值:foreign_key。

    因此,在您的情况下,看起来您确实需要 has_many 语句中的 foreign_key 属性,因为它与类的名称不同。

    但是,您的belongs_to 语句中不需要foreign_key 声明。这是the ActiveRecord documentationbelongs_to 关系的:foreign_key 选项的描述:

    指定用于关联的外键。默认情况下,这被猜测为带有“_id”后缀的关联名称。所以定义了belongs_to :person 关联的类将使用“person_id”作为默认的:foreign_key。同样,belongs_to :favorite_person, :class_name => "Person" 将使用外键 "favorite_person_id"。

    我假设你真正想为你的 Comment 课程写的是这样的:

    class Comment < ActiveRecord::Base
      belongs_to :graphic, :foreign_key => :graphic_id
    

    在这种情况下,您可以将belongs_to 语句简化为:

    belongs_to :graphic
    

    【讨论】:

    • 我认为他的意思是asset_id,可能是图形也可能不是图形
    • 这两个引号太相似了。我不明白为什么:foreign_key 在带有has_many 的模型中被覆盖,而带有belongs_to 的模型实际上将在其表中包含外键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多