有没有办法为belongs_to关系指定association_foreign_key?

时间:2014-05-25 21:20:40

标签: ruby-on-rails activerecord associations belongs-to

我有一个使用belongs_to关系的模型。我希望能够同时指定foreign_keyassociation_foreign_key值。但是,我只能指定foreign_key关系的belongs_to值(http://guides.rubyonrails.org/association_basics.html#belongs-to-association-reference)有没有办法解决这个问题?

以下是我的例子:

我有一个客户端模型。其location_id密钥必须属于Region模型,其中id由place_id引用。我想做的是:

class ClientId < ActiveRecord::Base
  belongs_to :region, foreign_key: 'location_id', association_foreign_key: 'place_id'

但是,我无法在此处指定association_foreign_key ...

1 个答案:

答案 0 :(得分:1)

不需要在同一模型中双向声明关联。你必须声明: 其他相关模型中有has_one / many。

class Client < ActiveRecord::Base
  belongs_to :region, foreign_key: 'location_id'

class Region < ActiveRecord::Base
  has_many :clients, foreign_key: 'place_id'
相关问题