sql - 如何在 rails 中添加条件 where 子句

标签 sql ruby-on-rails ruby conditional rails-activerecord

我是一名 Rails 新手,我正在尝试使用 Rails 对表执行搜索,而我只是使用我的 sql 知识来执行此操作。但这看起来不像是 rails 或 ruby​​...

有没有更好的方法来做我在下面做的事情? (基本上,如果日期参数已填充,则只将日期参数传递给 sql)

def search(begin_date=nil, end_date=nil)

    subject = " and created_at "

    if !(begin_date.nil? || end_date.nil?)
      where_part = subject + "BETWEEN :begin_date AND :end_date"
    else if (begin_date.nil? && end_date.nil?) 
      where_part = ""
    else if(begin_date.nil?)
      where_part = subject + " <= :end_date"
    else if (end_date.nil?)
      where_part = subject + " >= :begin_date"
    end
    end
    end
    end

    User.joins(places: {containers: {label: :user}}).where("users.id= :user_id "+where_part, user_id: self.id, begin_date:begin_date, end_date:end_date).group(...).select(...)
end

编辑

用户.rb

has_many :containers
has_many :user_places
has_many :places, through: :user_places
has_many :labels

放置.rb

has_many :containers
has_many :user_places
has_many :users, through: :user_places

容器.rb

belongs_to :label
belongs_to :place
belongs_to :user

标签.rb

belongs_to :user
has_many :containers

基本上,我想计算每个位置给定用户标签内或具有直接关系的容器数量,并希望能够按开始日期和结束日期对其进行过滤。

这两个日期中的任何一个都可能为零,因此我需要在我的“查询”中解决这个问题。

我的问题是:我怎样才能以 Rails 的方式做到这一点?我看了一下 http://guides.rubyonrails.org/active_record_querying.html也许我可以在此处的某个地方使用 except 命令...但是使用 ActiveRecord 执行此关系模型似乎有点复杂...我怎么可能?我真的认为我应该使用 ActiveRecord,但如何使用?

谢谢

最佳答案

您可以对一个查询应用多个 where 调用,这样您就可以构建您的基本查询:

query = User.joins(...)
            .group(...)
            .select(...)
            .where('users.id = :user_id', :user_id => self.id)

然后根据您的日期间隔添加另一个 where 调用:

if(begin_date && end_date)
  query = query.where(:created_at => begin_date .. end_date)
  # or where('created_at between :begin_date and :end_date', :begin_date => begin_date, :end_date => end_date)
elsif(begin_date)
  query = query.where('created_at >= :begin_date', :begin_date => begin_date)
elsif(end_date)
  query = query.where('created_at <= :end_date', :end_date => end_date)
end

每个 where 调用都会使用 AND 将另一部分添加到您的整个 WHERE 子句中,例如:

q = M.where(a).where(b).where(c)

等同于 WHERE a AND b AND c

关于sql - 如何在 rails 中添加条件 where 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11689720/

相关文章:

ruby-on-rails - 在 try 和 and 之间推荐哪种语法。当我们在 Ruby on Rails 中处理 nil 值时?

mysql - ruby mysql 连接错误

ruby - 跟踪在每个网站上花费的时间

php - WHERE查询上的PHP错误代码

ruby-on-rails - 使用祖先 gem 订购子树导航

sql - MSSQL Server 在 InnerJoin 上不使用非聚集复合键索引 (PK + FK)

ruby-on-rails - rake 入 Rails : should I be using db:reset?

ruby-on-rails - Rails + 延迟作业 => 电子邮件 View 模板未更新

sql - 从 SQL Server 触发器将行写入 CSV

mysql - 我的 join sql 查询不会带来结果