传递给#or的关系必须在结构上兼容。 不兼容的值:
我有两个查询,我需要一个or
它们之间,即我想要第一个或第二个查询返回的结果。
第一个查询是一个简单的where()
,它获取所有可用的项目。
@items = @items.where(available: true)
第二个包括join()
并给出当前用户的项目。
@items = @items .joins(:orders) .where(orders: { user_id: current_user.id})
我尝试以各种forms将这些与Rails’ or()
方法结合起来,包括:
@items = @items .joins(:orders) .where(orders: { user_id: current_user.id}) .or( @items .joins(:orders) .where(available: true) )
但我一直遇到这个错误,我不知道如何解决它。
Relation passed to #or must be structurally compatible. Incompatible values: [:references]
在Github上有一个已知的问题 。
根据此注释,您可能希望覆盖structurally_incompatible_values_for_or
以克服此问题:
def structurally_incompatible_values_for_or(other) Relation::SINGLE_VALUE_METHODS.reject { |m| send("#{m}_value") == other.send("#{m}_value") } + (Relation::MULTI_VALUE_METHODS - [:eager_load, :references, :extending]).reject { |m| send("#{m}_values") == other.send("#{m}_values") } + (Relation::CLAUSE_METHODS - [:having, :where]).reject { |m| send("#{m}_clause") == other.send("#{m}_clause") } end
总是有一个使用SQL的选项:
@items .joins(:orders) .where( "orders.user_id = ? OR items.available = true", current_user.id )
您可以用这种古老的方式编写查询以避免错误
@items = @items.joins(:orders).where("items.available = ? OR orders.user_id = ?", true, current_user.id)
希望有所帮助!
- 如何在Postgres中进行查询以按月创建分组记录? (:created_at datetime列)
- postgresql nextval生成现有值
- 使用postgreSQL奇怪行为增加计数器和rails“first”
- Rails + PostgreSQL SSL解密失败
- 你如何访问你的heroku数据库(特别是postgres)?
- 如何调整在Heroku上运行的Ruby on Rails应用程序,它使用生产级Heroku Postgres?
- 在heroku上的PostgreSQL数据库中存储超过255个字符
- 无法在ubuntu上使用PostgreSQL连接Rails应用程序
- 查询包含JSON对象数组的jsonb列