开发者

Ruby on Rails: named Scope OR is getting translated into AND when it becomes SQL

{ :conditions =>  ["#{"(visibility = #{Shared::PUBLIC}) || " if include_non_employee_public} (visibility IN (#{employee_pr开发者_Go百科ivacy}) AND user_id IN (#{users}))"] }

there is my condition for my named scope. now i've tried both || and OR in the named scope, but the console always shows AND.

any ideas?


{ :conditions =>  ["#{"(visibility = #{Shared::PUBLIC}) || " if include_non_employee_public} (visibility IN (#{employee_privacy}) AND user_id IN (#{users}))"] }

It's confusing trying to reverse engineer what you're trying to do here. Generally though an sql query should always use "OR" rather than "||". || will only work in your ruby code. Also, normally you should use ? and then put the value afterwards rather than use string evaluation. That will work better with arrays for example which you seem to be using here. Eg

{ :conditions =>  ["#{"(visibility = ?) || " if include_non_employee_public} (visibility IN (?) AND user_id IN (?))"], Shared::PUBLIC, employee_privacy, users]  }

Ok, next step is to work out what you are trying to do. Let's say for the sake of argument that include_non_employee_public is true. Then you will get

{ :conditions =>  ["(visibility = ?) || (visibility IN (?) AND user_id IN (?))"], Shared::PUBLIC, employee_privacy, users]  }

Let's swap that || for an or so it will work in sql:

{ :conditions =>  ["(visibility = ?) or (visibility IN (?) AND user_id IN (?))"], Shared::PUBLIC, employee_privacy, users]  }

Is that what you are trying to do? This now won't work though because in the case where include_non_employee_public is false, you now have a spare value (Shared::Public) in the second part of the argument list. I would, for the sake of comprehensibility, break this into an if statement:

if include_non_employee_public
  conditions = ["(visibility = ?) or (visibility IN (?) AND user_id IN (?))"], Shared::PUBLIC, employee_privacy, users] 
else
  conditions = ["visibility IN (?) AND user_id IN (?)"], employee_privacy, users] 
end

Now you can say :conditions => conditions in your query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜