rails 3 - 'or' scopes - ruby-on-rails-3

We are updating a rails 2 app. We have happily been using fake_arel which provides a very nice 'or' scope.
Now, with rails 3 I can't find a way to replicate this.
We have code like this:
scope.or(Event.horse, Event.dog, Event.trap).today
The model looks like this:
class Event < ActiveRecord::Base
named_scope :horse, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_horse_ids] }}
named_scope :dog, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_dog_ids] }}
named_scope :trap, lambda { {:conditions => ["sport_category_id in (?)", SportCategory.find_trap_ids] }}
end
These scopes need to be separate and are used all over the place. This model actually has dozens of scopes on it that are used in combination, so rewriting it all is the last thing we want to do.
It seems strange that you can't 'or' scopes together.
Can someone propose a way to do this as nicely in Rails 3? Even using arel I don't see how to.
We are using meta_where in a different project, but it doesn't offer any such thing either.

Well, the way to do that is, in your model (adapt it to your needs!) :
where(:event => ['horse', 'dog', 'trap'])
An array will produce a IN statement, which is what you want there. Furthermore, you can use rails 3 scopes to achieve that :
scope :my_scope, where(:event => ['horse', 'dog', 'trap'])
Then you can use it this way :
mymodel.my_scope # and possibility to chain, like :
mymodel.my_scope.where(:public => true)

I ripped out the 'or' function from fake_arel and got it working with rails 3.0x (not sure if it will work with 3.1 as we don't use that here)
I case anyone is interested I have put it in a gist:

I was unable to get the code from the Github-gist by Phil working, but it inspired me to come up with the following, which I think is a simpler, solution. It uses a class-method that returns an ActiveRecord::Relation class nonetheless.
def self.or alt_scope
either = scoped.where_clauses.join(' AND ')
alternative = alt_scope.where_clauses.join(' AND ')
Locatie.unscoped.where("(#{either}) OR (#{alternative})").
joins(scoped.joins_values).joins(alt_scope.joins_values).
group(scoped.group_values).group(alt_scope.group_values).
having(scoped.having_values).having(alt_scope.having_values).
includes(scoped.includes_values).includes(alt_scope.includes_values).
order(scoped.order_values).order(alt_scope.order_values).
select(scoped.select_values).select(alt_scope.select_values)
end
Just add this to your class. You'll then get the ability to create a multiple OR query as follows:
Event.horse.or(Event.dog).or(Event.trap)
Which you can consequently 'store' in a scope:
scope :horse_dog_or_trap, horse.or(Event.dog).or(Event.trap)
and also extend the scope even further, such as:
Event.horse.or(Event.dog).or(Event.trap).today

Related

How can I query a rails 3 app efficiently?

I have a search form that queries one table in the database but there are many parameters (language, level, creator etc). The code below works provided the fields in question are filled in but I want to change it to:
a) add more parameters (there are several);
b) allow for a field to be empty
Here's the code in the controller:
#materials = Material.find(:all, :conditions => {:targ_lang => params["targ_lang"],
:inst_lang => params["inst_lang"],
:level => params["level"]})
Totally new to this I'm afraid but a lot of the documentation suggests I should be using "where".
Since Rails 3 you can use the where() function:
#materials = Material.where(targ_lang: params["targ_lang"], inst_lang: params["inst_lang"], level: params["level"])
Also, you could take a look at scopes
These allow you to set what you want to do in the model and call it in the controller for example:
class Material < ActiveRecord::Base
scope :active, where(active_state: true)
end
Then in the controller you do something like:
#active_materials = Material.active
This can be useful if you are joining several models and want to keep your controllers less messy.
To conclude, like #RVG said, seachlogic is quite useful as well as, there are others like Sphinx and Elastic Search. You should take a quick look at these and use the one you feel most confortable with.
If you are using search functionality in your app I suggest using SearchLogic gem
It is easy to use and effective..
SearchLogic
RailsCasts for searchlogic

Rails ActiveRecord query

My question is twofold... Primarily, I am trying to figure out how to ask > or < when filtering this query. You can see at the end I have .where(:created_at > 2.months.ago) and that is improper syntax, but I'm not sure the correct way to call something similar.
Secondly, this is a bit of a long string and is going to get longer as the are more conditions I have to factor in. Is there a cleaner way of building this, or is a long string of conditions like this pretty standard?
class PhotosController < ApplicationController
def showcase
#photos = Photo.order(params[:sort] || 'random()').search(params[:search]).paginate(:per_page => 12, :page => params[:page]).where(:created_at > 2.months.ago)
end
Thanks.
Unfortunately you've hit a sore point in the ActiveRecord querying api. There is no standard, out of the box way to do this. You can do date ranges very easily, but < and > have no easy path. However Arel, the underlying SQL engine, can do this very easily. You could write a simple scope to handle it thusly:
scope :created_after, lambda {|date| where arel_table[:created_at].gt(date) }
And you could refactor this easily to take a column, or gt versus lt, etc.
Other people have solved this problem already, however, and you could take advantage of their work. One example is MetaWhere, which adds a bunch of syntactic sugar to your queries. For example, using it you might write:
Article.where(:title.matches => 'Hello%', :created_at.gt => 3.days.ago)
On #2, scopes do tend to get long. You might look into the gem has_scope, which helps to alleviate this by defining scopes on the controller in an analogous way to how they are defined on the model. An example from the site:
# The model
# Note it's using old Rails 2 named_scope, but Rails 3 scope works just as well.
class Graduation < ActiveRecord::Base
named_scope :featured, :conditions => { :featured => true }
named_scope :by_degree, proc {|degree| { :conditions => { :degree => degree } } }
end
# The controller
class GraduationsController < ApplicationController
has_scope :featured, :type => :boolean
has_scope :by_degree
def index
#graduations = apply_scopes(Graduation).all
end
end
You can do where(["created_at > ?", 2.months.ago]) for your first question.
For your second question there are several solutions :
You can use scopes to embed the conditions in them and then combine them.
You can break the line in multiple lines.
You can keep it like this if you have a large screen and you don't work with any other people.

named_scope and .first?

I can return a collection of objects, with only one (:limit => 1) but is there a way to return the .first() object only, like not within a collection?
named_scope :profile, :conditions => {:association => 'owner', :resource_type => 'Profile'}, :limit => 1 # => collection of 1 profile but I want the profile only NOT in a collection or array
the workaround is simply to apply .first() to the results, but I'd just like to clean up the code and make it less error prone.
You'll probably need to create a class method instead:
def self.profile
where(:association => 'owner', :resource_type => 'Profile').first
end
Note that with Rails 3 you should be using the where(...) syntax, and that when doing .first, you don't need to specify the limit.
First off, if you're using Rails 3 you should be using scope instead of named_scope. Same thing, different, err, name (named_scope will still work, but it is deprecated). Now that that is out of the way…
A scope (or named scope) takes two arguments (a symbol and either a lambda or a hash) and defines a class method on that model that returns an ActiveRecord::Relation, which is why you're able to chain methods on it.
first, like find or all, returns an actual result from the database. For this reason it won't work in a scope.
All that said, you can define your own class method on your model that gives the behavior you're wanting (as 2 people already answered while I was typing this). This is actually recommended over using scopes by many well-respected devs in the Rails community. Since using the scope class macro just defines class methods itself anyways, there isn't really a downside to this, and it has the benefit of flexibility (like in your case here).
Define a class method to do this:
def profile
where(:association => "owner", :resource_type => 'Profile').first
end
The first already does an implicit limit 1 on the query, AND will order it by the primary key of the table so you'll always get the first.

How to make a Rails 3 Dynamic Scope Conditional?

I'd like to make a dynamic named scope in rails 3 conditional on the arguments passed in. For example:
class Message < AR::Base
scope :by_users, lambda {|user_ids| where(:user_id => user_ids) }
end
Message.by_users(user_ids)
However, I'd like to be able to call this scope even with an empty array of user_ids, and in that case not apply the where. The reason I want to do this inside the scope is I'm going to be chaining several of these together.
How do I make this work?
To answer your question you can do:
scope :by_users, lambda {|user_ids|
where(:user_id => user_ids) unless user_ids.empty?
}
However
I normally just use scope for simple operations(for readability and maintainability), anything after that and I just use class methods, so something like:
class Message < ActiveRecord::Base
def self.by_users(users_id)
if user_ids.empty?
scoped
else
where(:user_id => users_id)
end
end
end
This will work in Rails 3 because where actually returns an ActiveRecord::Relation, in which you can chain more queries.
I'm also using #scoped, which will return an anonymous scope, which will allow you to chain queries.
In the end, it is up to you. I'm just giving you options.

Rails: Find by related model attribute?

So, I tried to search for an example of how to do this, and I'm not sure I even know how to describe what I'm trying to do. I'm an utter noob when it comes to SQL, and I'm sure this is really basic but I'm totally lost:
I have a model, Photo, which has_many :tags, :through => :taggings. Tags have a name and an id.
I want to do something like: Photo.where( #tag_name in [array] )
... but like I said I have no idea how to write something like that, or what to search to see an example on Google.
Can anyone give me an example of that kind of query, and what it might be called?
Thanks!
Just tried this on a similar model of my own and seemed to work fine:
Photo.joins(:tags).where('tags.name' => ['herp','derp']).group(:id)
Also, here's a great resource on the AREL querying interface rails 3 uses, with information on these and other ActiveRecord calls related to querying.
So, as a twist on Brett's method, it turns out the following works without breaking PostgreSQL:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end
Problem solved! See this article for a great explanation as to why this is a better idea than 'group'.