ruby-on-rails - 在 Rails 上重新定位或取消范围包含数组条件的查询

标签 ruby-on-rails ruby activerecord

我正在尝试rewhereunscope 一个查询,其中原始条件不能使用散列条件写入:

Reservation.where('block_id IS NULL OR block_id != ?', 'something')

> SELECT `reservations`.* FROM `reservations` WHERE (block_id IS NULL OR block_id != 'something')

尝试重新定位无效:

Reservation.where('block_id IS NULL OR block_id != ?', 'something').rewhere(block_id: 'anything')

> SELECT `reservations`.* FROM `reservations` WHERE (block_id IS NULL OR block_id != 'something') AND `reservations`.`block_id` = 'anything'

但是这个带有散列条件的例子是可行的:

Reservation.where.not(block_id: 'something').rewhere(block_id: 'anything')

> SELECT `reservations`.* FROM `reservations` WHERE `reservations`.`block_id` = 'anything'

我知道这可能是因为在 array condition rails 不知道我在哪一列调用 where,因此 rewhere 找不到任何东西替换。

有什么方法可以明确告诉我在数组条件中过滤哪一列?或者用散列条件重写第一个查询(IS NULL OR != value)?

注意:请不要建议 unscoped,因为我试图取消范围/重新定位此特定条件,而不是整个查询。

谢谢!

最佳答案

抱歉,不清楚您是否还有其他想要保留的 where 子句。您可以使用 relations.values[:where] 访问 where 子句的数组并对其进行操作,例如:

Reservation.where('block_id IS NULL OR block_id != ?', 'something')
           .tap do |relation|
                  # Depending on your version of Rails you can do 
                  where_values = relation.where_values
                  # Or
                  where_values = relation.values[:where]
                  # With the first probably being better
                  where_values.delete_if { |where| ... }
                end
           .where(block_id: 'anything')

又名黑客

关于ruby-on-rails - 在 Rails 上重新定位或取消范围包含数组条件的查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42763160/

相关文章:

ruby-on-rails - Slack 传入 Webhook API

ruby-on-rails - 如何响应 Rails 中的 ajax 调用

sql - 1 次查询中的不同、顺序

mysql - Ruby on Rails/ActiveRecord 和表分区

mysql - rails : Find all records matching condition for any of the associated objects

javascript - 自定义数字输入

ruby-on-rails - 在 Rails 中播种外键?

ruby-on-rails - Rails ActionController::UnknownFormat 错误与 respond_to

ruby - 如何使用 block 来更改 ruby​​ 中的执行上下文?

ruby - 通过 FFI 从 rust 到 ruby ,弦变空