【发布时间】:2017-12-23 02:50:59
【问题描述】:
我试图弄清楚如何将多个范围链接在一起。我想要做的是有一个搜索框,它将 params[:user_search] 传递给控制器,该控制器在用户模型中调用 by_keyword 范围。 by_keyword 范围就像我现在拥有的那样工作,但我想让它也搜索我拥有的所有其他范围。所以基本上 by_keyword 范围应该查询用户输入的任何关键字的所有范围。
在我的 users_controller 索引操作中
if params[:user_search].present?
@users = @users.by_keyword(params[:user_search])
end
在我的用户模型中
scope :by_keyword, -> (keyword) { where('experience LIKE ? OR current_job_title LIKE ?', "%#{keyword}%", "%#{keyword}%" ).order(updated_at: :desc) if keyword.present? }
我想找到一种方法将所有这些链接到 by_keyword 范围
# these scopes call child classes of User such as skills, languages, patents, etc...
scope :by_skill, -> (sk) { joins(:skills).distinct.where( 'skills.name LIKE ?', "%#{sk}%" ).order(updated_at: :desc) if sk.present? }
scope :by_language, -> (lang) { joins(:languages).distinct.where( 'languages.language LIKE ?', "%#{lang}%" ).order(updated_at: :desc) if lang.present? }
scope :by_certification_or_cert_authority, -> (cert) { joins(:certifications).distinct.where( 'certifications.certification_name LIKE ? OR certifications.certification_authority LIKE ?', "%#{cert}%", "%#{cert}%" ).order(updated_at: :desc) if cert.present? }
scope :by_education_level, -> (ed) { joins(:qualifications).distinct.where( 'qualifications.education LIKE ?', "%#{ed}%" ).order(updated_at: :desc) if ed.present? }
scope :by_university_major, -> (maj) { joins(:qualifications).distinct.where( 'qualifications.university_major LIKE ?', "%#{maj}%" ).order(updated_at: :desc) if maj.present? }
我读完了http://guides.rubyonrails.org/active_record_querying.html#scopes
他们给出的例子就是这个,但我不知道如何将超过 2 个作用域链接在一起。
class Article < ApplicationRecord
scope :published, -> { where(published: true) }
scope :published_and_commented, -> { published.where("comments_count > 0") }
end
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-5