ror - include foreign key at both ends of has_many and belongs_to?

假装没事ソ 提交于 2019-12-10 17:15:28

问题


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

回答1:


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.




回答2:


In a has_many statement for rails, :foreign_key is indeed an option which has this description in the ActiveRecord documentation:

Specify the foreign key used for the association. By default this is guessed to be the name of this class in lower-case and “_id” suffixed. So a Person class that makes a has_many association will use “person_id” as the default :foreign_key.

So in your case, it looks as though you do need the foreign_key attribute on your has_many statement, since it differs from the name of the class.

However, you shouldn't need the foreign_key declaration in your belongs_to statement. Here is the description for the :foreign_key option for a belongs_to relationship in the ActiveRecord documentation:

Specify the foreign key used for the association. By default this is guessed to be the name of the association with an “_id” suffix. So a class that defines a belongs_to :person association will use “person_id” as the default :foreign_key. Similarly, belongs_to :favorite_person, :class_name => "Person" will use a foreign key of “favorite_person_id”.

I'm assuming that what you really meant to write for your Comment class is this:

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

In this case you could simplify the belongs_to statement to simply this:

belongs_to :graphic


来源:https://stackoverflow.com/questions/8993870/ror-include-foreign-key-at-both-ends-of-has-many-and-belongs-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!