【发布时间】:2015-08-27 06:38:41
【问题描述】:
我在 ActiveRecord 中使用类似范围时遇到问题。我有 3 个模型:
人:
class Person < ActiveRecord::Base
has_many :survey_packs
def self.by_first_name(text)
where(first_name: text)
end
end
调查包:
class SurveyPack < ActiveRecord::Base
has_many :survey_instances, inverse_of: :survey_pack
belongs_to :person
end
和调查实例:
class SurveyInstance < ActiveRecord::Base
belongs_to :survey_pack, inverse_of: :survey_instances
belongs_to :student, class_name: 'Person', foreign_key: :person_id
scope :teacher_full_name, ->(text) { SurveyInstance.joins(:person).merge(Person.by_first_name(text)) }
scope :student_full_name, ->(text) { SurveyInstance.joins(:student).merge(Person.by_first_name(text)) }
end
问题是我无法将这些范围连接在一起:
scope :teacher_full_name, ->(text) { SurveyInstance.joins(:person).merge(Person.by_first_name(text)) }
scope :student_full_name, ->(text) { SurveyInstance.joins(:student).merge(Person.by_first_name(text)) }
例如,我有一个调查实例,学生姓名为:“学生”,教师姓名为:“教师”:
SurveyInstance.teacher_full_name('Teacher') #this will work
SurveyInstance.student_full_name('Student') #this will also work
SurveyInstance.teacher_full_name('Teacher').student_full_name('Student') #this will not work...
我不知道如何解决这个问题...
【问题讨论】:
标签: sql ruby-on-rails ruby-on-rails-4 activerecord