Rails 4通过关联进行多态化

时间:2015-04-11 12:30:23

标签: ruby-on-rails nested polymorphic-associations

我希望有人可以提供帮助,因为我无法快速完成任务。我有以下设置,从上到下,我将删除一个虚假的代码。我想保留探测的多态模型,因为rcs_prospecting和ara_prospecting都使用了这个模型中的字段,并且还有自己的字段。

contact.rb

class Contact < ActiveRecord::Base
  has_one :ara_prospecting
  has_one :rcs_prospecting

  .... 
end

ara_prospecting.rb

class AraProspecting < ActiveRecord::Base
  belongs_to :contact
  has_one :prospecting, as: :prospectable
  accepts_nested_attributes_for :prospecting, :reject_if => :all_blank, :update_only => true
end

rcs_prospecting.rb

class RcsProspecting < ActiveRecord::Base
  belongs_to :contact
  has_one :prospecting, as: :prospectable
  accepts_nested_attributes_for :prospecting, :reject_if => :all_blank, :update_only => true
end

prospecting.rb

class Prospecting < ActiveRecord::Base
  belongs_to :prospectable, polymorphic: true 
  belongs_to :user 
end

我要做的是通过ara_prospecting和rcs_prospecting关联从联系人模型创建一个与用户模型关联的has_one。基本上我想要

has_one :ara_user, through...(ara_prospecting -> prospecting -> user)
has_one :rcs_user, through...(rcs_prospecting -> prospecting -> user)

我看过各种文章并尝试了不同的东西,但似乎无法破解它。

非常感谢任何帮助。

提前谢谢

1 个答案:

答案 0 :(得分:0)

我没有使用has_one :through关联,而是完全删除ara_prospectingrcs_prospecting

class Contact < ActiveRecord::Base
  has_many :prospecting

  .... 
end

class Prospecting < ActiveRecord::Base
  belongs_to :contact

  scope :ara, -> {where(category: "ara")}
  scope :rcs, -> {where(category: "rcs")}
end

Prospecting迁移中,添加t.string :category并在创建对象时为其分配ararcs。我定义的范围可以让您轻松分离它们。