首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Rails 4通过关联实现多态

Rails 4通过关联实现多态
EN

Stack Overflow用户
提问于 2015-04-11 20:30:23
回答 1查看 46关注 0票数 0

如果我没什么进展,我希望有人能帮上忙。我有以下设置,从上到下,我将删除一个伪代码。我想保留多态模型的勘探,因为rcs_prospecting和ara_prospecting都使用此模型中的字段,也有自己的字段。

contact.rb

代码语言:javascript
运行
复制
class Contact < ActiveRecord::Base
  has_one :ara_prospecting
  has_one :rcs_prospecting

  .... 
end

ara_prospecting.rb

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
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

代码语言:javascript
运行
复制
class Prospecting < ActiveRecord::Base
  belongs_to :prospectable, polymorphic: true 
  belongs_to :user 
end

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

代码语言:javascript
运行
复制
has_one :ara_user, through...(ara_prospecting -> prospecting -> user)
has_one :rcs_user, through...(rcs_prospecting -> prospecting -> user)

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

任何帮助都将不胜感激。

提前谢谢你

EN

回答 1

Stack Overflow用户

发布于 2015-04-11 21:37:27

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

代码语言:javascript
运行
复制
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。我定义的作用域可以让你很容易地将它们分开。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/29577897

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档