【问题标题】:Using similar scopes in ActiveRecord在 ActiveRecord 中使用类似的范围
【发布时间】: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


    【解决方案1】:

    不确定这是否有效,但逻辑类似于:

    class SurveyInstance < ActiveRecord::Base
      belongs_to :survey_pack, inverse_of: :survey_instances
      belongs_to :student, class_name: 'Person', foreign_key: :person_id
    
      scope :full_name, ->(type, text) { SurveyInstance.joins(type).merge(Person.by_first_name(text)) }
    end
    

    提取关联,以便符号通过作用域调用传递。

    调用作用域:

    SurveyInstance.full_name(:person, 'Teacher')
    SurveyInstance.full_name(:student, 'Student')
    

    【讨论】:

    • 使用这个范围一次就可以正常工作。但试图链接它:SurveyInstance.full_name(:person, 'Teacher').full_name(:student, 'Student') 它不会搜索正确的记录。
    猜你喜欢
    • 1970-01-01
    • 2014-10-11
    • 2012-07-29
    • 1970-01-01
    • 2011-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多