【问题标题】:How to include a if condition inside where clause in rails如何在rails的where子句中包含if条件
【发布时间】:2022-01-04 12:58:07
【问题描述】:

我有以下方法:

def add_books(year, industry, author_id=nil)
  Books.where(publication_year:year, author: author_id)
end

如果未通过,我如何更新查询以不按author_id 过滤?

【问题讨论】:

标签: ruby-on-rails ruby-on-rails-3


【解决方案1】:

我会这样做:

def add_books(year, industry, author_id = nil)
  conditions = { publication_year: year }
  conditions[:author_id] = author_id if author_id.present?

  Books.where(conditions)
end

但是,add_books 方法的名称暗示了一个 create 你没有。也没有使用industry。有点可疑:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-04-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多