我有一个Item
s 的数据库。每个项目belongs_to
一个User
。每个项目都有一个visibility
和status
字段。为了可搜索,项目必须满足以下规则:
status must be :available
AND
(visibility must be :everyone
OR
(visibility must be :friends AND user_id must be in current_user.friends)
)
换句话说,您会看到所有可用和公共项目,并且您会看到朋友的“私人”项目。
如何检索符合此条件的项目?
我尝试了以下方法:
class Item < ActiveRecord::Base
belongs_to :user
attr_accessible :description, :photo, :title, :user_id, :visibility
#...
scope :searchable, lambda { |user|
where('status IN ? AND (visibility IN ? OR (visibility IN ? AND user_id IN ?))',
[:available, :lent],
[:everyone],
[:friends],
user.friends)
}
end
在我的控制器中:
@items = Item.searchable(current_user)
但我有一个错误:
IN 生成的子句周围没有括号
ActiveRecord::StatementInvalid in Items#search
SQLite3::SQLException: near ",": syntax error: SELECT "items".* FROM "items" WHERE (status IN 'available','lent' AND (visibility IN 'everyone' OR (visibility IN 'friends' AND user_id IN 'foo')))