相关疑难解决方法(0)

关联特定类型的多态belongs_to

我对Rails比较陌生.我想为使用多态关联的模型添加关联,但只返回特定类型的模型,例如:

class Note < ActiveRecord::Base
  # The true polymorphic association
  belongs_to :subject, polymorphic: true

  # Same as subject but where subject_type is 'Volunteer'
  belongs_to :volunteer, source_association: :subject
  # Same as subject but where subject_type is 'Participation'
  belongs_to :participation, source_association: :subject
end
Run Code Online (Sandbox Code Playgroud)

我通过阅读有关ApiDock的关联尝试了大量的组合,但似乎没有任何东西完全符合我的要求.这是我迄今为止最好的:

class Note < ActiveRecord::Base
  belongs_to :subject, polymorphic: true
  belongs_to :volunteer, class_name: "Volunteer", foreign_key: :subject_id, conditions: {notes: {subject_type: "Volunteer"}}
  belongs_to :participation, class_name: "Participation", foreign_key: :subject_id, conditions: {notes: {subject_type: "Participation"}}
end
Run Code Online (Sandbox Code Playgroud)

我希望它通过这个测试:

describe Note do
  context 'on volunteer' do
    let!(:volunteer) …
Run Code Online (Sandbox Code Playgroud)

ruby-on-rails polymorphic-associations ruby-on-rails-3

19
推荐指数
3
解决办法
7511
查看次数