4 ms·
I like the sequel gem's syntax even better: Post.where(:id => 1).or(:id => 2)
by cortesoft 10y ago
I like the sequel gem's syntax even better: Post.where(:id => 1).or(:id => 2)
- stouset 10y agoSequel's syntax is strictly less powerful, since Rails' accepts any scope instead of just a hash of conditions. Post.where(id: 1).or Post.joins(:author).where(author: { name: 'John' })
- cyberferret 10y agoCorrect me if I am wrong, but can't the Sequel ORM accomplish this as well? Post.join(:author).where(:author__name => "John") (the above is purely from memory and may have syntax errors). In any case, it lets you drop into raw SQL as a last resort.
- cortesoft 10y agoYes, you are correct.
- jeremyevans 10y agoThat doesn't appear to work: Post.where(id: 1).or Post.joins(:author).where(author: { name: 'John' }) ArgumentError: Relation passed to #or must be structurally compatible. Incompatible values: [:joins, :references] It appears that only the filter clauses are allowed to be different (similar errors if :select, :order, :group, :limit are different), in which case it's no more powerful than Sequel, just more of a pain to use. You can easily implement ActiveRecord's behavior in Sequel if you want to combine filter clauses for arbitrary datasets: ds = Post.where(id: 2) Post.where(id: 1).or(ds.opts[:where]) It's also interesting what happens if you mix where and having clauses (I'm not saying it doesn't make sense, but it may bite someone): Post.where(id: 1).or(Post.having(id: 2)).to_sql # SELECT "posts".* FROM "posts"
- rabidferret 10y agoI talk about this at length in one of my recent talks but the short version is we wanted to optimize for reuse via named scopes
- Raticide 10y agoThis falls apart when you need multiple scopes as it can't tell how to group the 'AND' and 'OR's. The new Rails syntax avoids this problem.
- jeremyevans 10y agoThat isn't a problem in Sequel, as you can pass a complex expression to #or, in which case it works as you would expect it to: Post.where(id: 1).or(Sequel.&({:id=>2}, {:name=>'Foo'})) # SELECT * FROM posts WHERE ((id = 1) OR ((id = 2) AND (name = 'Foo')))
- epidemian 10y agoYay, Jeremy Evans spreading some Sequel knowledge ^_^ Big fan of Sequel; it's super sleek. As a side-note to Jeremy's comment, while (i guess) he used Sequel.& to demonstrate that OR and AND conditions can be combined freely, there are more succinct ways of expressing that particular query: # Using the a "virtual row" block: Post.where(id: 1).or{(id =~ 2) & (name =~ 'Foo')} # Or, if you don't fancy that kind of block magic, simply passing a Hash, # the same way as with .where Post.where(id: 1).or(id: 2, name: 'Foo')