Refactor Rails基于条件的ActiveRecord

时间:2016-02-01 04:23:20

标签: ruby-on-rails ruby

我有以下内容。如何最好地重构它:

  def self.search(search, organization_id, is_admin)
    if is_admin == false
      where("record_no LIKE ?", "%#{search}%").
        where("organization_id = ?", organization_id)
    else
      where("record_no LIKE ?", "%#{search}%")
    end
  end

基本上这意味着,当用户是管理员时,我希望它显示所有没有organization_id的记录。

4 个答案:

答案 0 :(得分:2)

你可以这样试试。

search_criteria = where("record_no LIKE ?", "%#{search}%")
search_criteria.where("organization_id = ?", organization_id) unless is_admin

答案 1 :(得分:1)

它看起来像这样:

def self.search(search, organization_id, is_admin)
  criteria = where("record_no LIKE ?", "%#{search}%")
  criteria = criteria.where("organization_id = ?", organization_id) unless is_admin
  criteria
end

答案 2 :(得分:0)

将条件合并到where

def self.search(search, organization_id, is_admin)
  where("record_no LIKE ? AND (? OR organization_id = ?)", "%#{search}%", is_admin, organization_id)
end

答案 3 :(得分:0)

试试这个:

if !is_admin
    where(["record_no LIKE ? and organization_id = ?", "%#{search}%", organization_id])
else
    where("record_no LIKE ?", "%#{search}%")
end