Activerecord找到多个条件和多对多关系

时间:2016-02-16 22:47:25

标签: ruby-on-rails postgresql activerecord

我正在尝试修复一个小查询。

我有这堂课:

class Content < ActiveRecord::Base
 has_many :sections
 belongs_to :brand
end

在我的控制器中我有

def show
 @content = Content.find params[:id]
 @related_contents = Content.where('brand_id = ? OR sections_ids IN ? AND id != ?', @content.brand.id, @content.section_ids, @content.id)
end

我必须找到所有相同品牌的内容或相同的部分,不包括我在视图中显示的内容的选择......

但我收到PG::SyntaxError错误

SELECT "contents".* FROM "contents" WHERE (brand_id = 1 AND sections_ids IN 11 AND id != 15)  ORDER BY "contents"."published_at" DESC
PG::SyntaxError: ERROR:  syntax error at or near "11"
LINE 1: ...M "contents" WHERE (brand_id = 1 AND sections_ids IN 11 AND id ...
                                                             ^
: SELECT "contents".* FROM "contents" WHERE (brand_id = 1 AND sections_ids IN 11 AND id != 15)  ORDER BY "contents"."published_at" DESC

2 个答案:

答案 0 :(得分:0)

'brand_id = ? OR section_ids IN ? AND id != ?'

您的查询中有多个“部分”。我猜它不是专栏。

答案 1 :(得分:0)

问题是你的IN条款。

我认为应该是:

 @related_contents = Content.where('brand_id = ? OR sections_ids IN (?) AND id != ?', @content.brand.id, @content.section_ids, @content.id)

请注意IN后问号周围的括号。