gpt4 book ai didi

ruby-on-rails - ror - 在 has_many 和 belongs_to 的两端包含外键?

转载 作者:数据小太阳 更新时间:2023-10-29 07:29:13 24 4
gpt4 key购买 nike

我继承的代码有:

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

最佳答案

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

class Comment
belongs_to :asset, :polymorphic => true
end

class Graphic
has_many :comments, :as => :assets
end

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

关于ruby-on-rails - ror - 在 has_many 和 belongs_to 的两端包含外键?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8993870/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com