ROR - 包括的has_many和belongs_to的两端外键? [英] ror - include foreign key at both ends of has_many and belongs_to?

查看:146
本文介绍了ROR - 包括的has_many和belongs_to的两端外键?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我继承code有:

 类图形<的ActiveRecord :: Base的
  的has_many:评论:foreign_key => ASSET_ID,
  :条件=> 'asset_type_id = 5',
  :为了=> 'created_at'属性,:依赖=> :破坏

一流的注释和LT;的ActiveRecord :: Base的
  belongs_to的:图形:foreign_key => :ASSET_ID
 

在我看来,像的has_many不应该有foreign_key(它在belongs_to的好,我相信,引用),但我不知道,你知道吗?

即。它应该是

 类图形<的ActiveRecord :: Base的
  的has_many:评论,
  :条件=> 'asset_type_id = 5',
  :为了=> 'created_at'属性,:依赖=> :破坏

一流的注释和LT;的ActiveRecord :: Base的
  belongs_to的:图形:foreign_key => :ASSET_ID
 

解决方案

我认为你正在尝试做的东西是已经烤轨。您应该使用多态关联这里。

 类评论
  belongs_to的:资产,多态=>真正
结束

一流的图形
  的has_many:评论:为=> :资产
结束
 

这样,你需要声明foreign_key对双方都不利。

I'm inheriting code which has:

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

It seems to me like the has_many should not have the foreign_key (it's referenced in the belongs_to ok I believe) but I am not sure, do you know?

i.e. should it be

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

解决方案

I think you are trying to do something that is already baked in Rails. You should use Polymorphic Associations here.

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

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

This way, you need to declare foreign_key on neither side.

这篇关于ROR - 包括的has_many和belongs_to的两端外键?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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