Rails: named_scope, lambda and blocks - ruby-on-rails

I thought the following two were equivalent:
named_scope :admin, lambda { |company_id| {:conditions => ['company_id = ?', company_id]} }
named_scope :admin, lambda do |company_id|
{:conditions => ['company_id = ?', company_id]}
end
but Ruby is complaining:
ArgumentError: tried to create Proc object without a block
Any ideas?

it's a parser problem. try this
named_scope :admin, (lambda do |company_id|
{:conditions => ['company_id = ?', company_id]}
end)

I think the problem may be related to the difference in precedence between {...} and do...end
There's some SO discussion here
I think assigning a lambda to a variable (which would be a Proc) could be done with a do
... end:
my_proc = lambda do
puts "did it"
end
my_proc.call #=> did it

If you're on ruby 1.9 or later 1, you can use the lambda literal (arrow syntax), which has high enough precedence to prevent the method call from "stealing" the block from the lambda.
named_scope :admin, ->(company_id) do
{:conditions => ['company_id = ?', company_id]}
end
1 The first stable Ruby 1.9.1 release was 2009-01-30.

It's something related to precedence as I can tell
1.upto 3 do # No parentheses, block delimited with do/end
|x| puts x
end
1.upto 3 {|x| puts x } # Syntax Error: trying to pass a block to 3!

Related

Ruby on Rails ActionController: scope combined with inclusive or

I'd like to combine two scope condition with an inclusive or.
I tried with: scope :myscope, lambda { |u| where(cond1: u.id) or where(cond2: u.id)}, but it doesn't work. What can I do?
ActiveRecord provides some methods that bypasses the need to write SQL, but in this case you'll need to go put a very little effort and write a small piece of SQL.
scope :myscope, -> { |u| where("cond1 = ? OR cond2 = ?", u.id, u.id) }
You can also be more concise and use
scope :myscope, -> { |u| where("cond1 = :id OR cond2 = :id", id: u.id) }
There is nothing wrong in writing some SQL. Don't fall into the trap "if I can't write it in Ruby, it's ugly or not the Rails way".
There is a query method #or which you can use like this:
where(cond1: u.id).or(cond2: u.id)
Rails 5 will implement "OR" as #jphager2's answer stated, but meanwhile you have to get your hands a little dirty :
scope :myscope, lambda {where ["cond1 = ? OR cond2 = ?", u.id, u.id]}
You can do by this:-
scope :myscope, lambda { |u| where('cond1 = ? OR cond2 = ?', u.id, u.id)}

named_scope for date.today Rails 2.3.9

Working with a Rails 2.3.9 app and wondering how to write my named_scope such that I only get workouts from the current date. I am setting the timezone in in the application controller with a before_filter. The below doesn't throw an error, just doesn't filter:
workout.rb
named_scope :today_only, :conditions => [ "workouts.created_at <= ? AND workouts.created_at >= ?", Time.zone.now, 1.days.ago ]
application_controller.rb
before_filter :set_user_time_zone
You're not seeing the responses you want because Ruby is evaluating your call to Time.now when it evaluates your class definition, not when you're calling the scope. You need to pass a lambda to your named_scope call to get it to evaluate on every request:
# ensure that Time.now is evaluated on every call
named_scope :today_only, lambda {{ :conditions => ["workouts.created_at BETWEEN ? AND ?", Time.zone.now.at_beginning_of_day, Time.zone.now.end_of_day ] }}
Also, I think your Time boundaries may be incorrect. Are you looking for workouts that were created in the past 24 hours (relative to Time.now), or only workouts that were created "today?" Your example works for the former, the example above does the latter.

Check for nil result in ActiveRecord query

I have a few places in a model that does stuff like
def ServerInfo.starttime(param)
find(:all, :conditions => "name ='#{param}_started'", :select => "date").first.date.to_datetime
end
Now, for reasons not relevant to the question, it can happen that this particular row is not in the database at all and the code above fails with NoMethodError (undefined method `date' for nil:NilClass):. My current fix is
res = find(:all, :conditions => "name ='#{param}_started'", :select => "date")
check_time = res.first.nil? ? 0 : res.first.date.to_datetime
This works find, but I feel it's not right to sprinkle that code all over the place. Is there some more ruby-ish / rail-ish way to prevent dereferencing nil?
In order to avoid the NoMethodError for nil, you should define a begin rescue block,
def ServerInfo.starttime(param)
begin
find(:all, :conditions => "foo").first.date.to_datetime
rescue
0
end
end
I also like the Rails try method:
find(:all, :conditions => "foo").first.try(:date).try(:to_datetime) || 0
maybe this is cleaner:
check_time = res.first.date.to_datetime if res.first
btw, don't use:
:conditions => "name ='#{param}_started'" # SQL injection vulnerability.
use this one instead:
:conditions => ["name = ?", "#{param}_started"] # This is safer. Pure clean Ruby
it's safer
You may also define a scope. For instance in a Rails3 app you should try:
In your ServerInfo.rb model:
scope :starttime, lambda{|param|
if self.has_attribute?(param+'_started')
where("name = ?", param+'_started' ).select('date')
else
false
end
}
// Remember to never put your params directly in your sql query, that is bad practice since you risk some sql injection //
Then in a controller:
res = ServerInfo.starttime('a_param')
check_time = res.first.date.to_datetime if res
I didn't try that code, then you may need to adapt it to your need (or to your Rails2 app)

Dynamic find conditions in active record

I have an index action in rails that can handle quite a few params eg:
params[:first_name] # can be nil or first_name
params[:age] # can be nil or age
params[:country] # can be nil or country
When finding users I would like to AND all the conditions that are not nil. This gives me 8 permutations of the find conditions.
How can I can I keep my code DRY and flexible and not end up with a bunch of if statements just to build the conditions for the find. Keep in mind that if no conditions are specified I just want to return User.all
How about something like:
conditions = params.only(:first_name, :age, :country)
conditions = conditions.delete_if {|key, value| value.blank?}
if conditions.empty?
User.all
else
User.all(:conditions => conditions)
end
I would normally use named scopes for something like this:
class User < ActiveRecord::Base
named_scope :name_like, lambda {|name| {:conditions => ["first_name LIKE ?", "#{name}%"]}}
named_scope :age, lambda {|age| {:conditions => {:age => age}}}
named_scope :in_country, lambda {|country| {:conditions => {:country => country}}}
end
class UsersController < ActionController
def index
root = User
root = root.name_like(params[:first_name]) unless params[:first_name].blank?
root = root.age(params[:age]) unless params[:age].blank?
root = root.country(params[:country]) unless params[:age].blank?
#users = root.paginate(params[:page], :order => "first_name")
end
end
That's what I normally do.
This seems to work quite nicely:
conditions = params.slice(:first_name, :age, :country)
hash = conditions.empty? ? {} : {:conditions => conditions}
#users = User.all hash
Using James Healy answer, I modify the code to be used in Rails 3.2 (in case anyone out there need this).
conditions = params.slice(:first_name, :age, :country)
conditions = conditions.delete_if {|key, value| value.blank?}
#users = User.where(conditions)
You could try Ambition, or a number of other ActiveRecord extensions.
This works for me too
conditions = params[:search] ? params[:search].keep_if{|key, value| !value.blank?} : {}
User.all(:conditions => conditions)
If you happen to be on an ancient project (Rails 2.x) and very messy, you could do something like the following for adding new fields to the original query.
Original code:
User.find(:all,
:conditions => ['first_name LIKE ? AND age=? AND country=?',
"#{name}%", age, country]
Adding a new dynamic condition on zip_code field:
zip_code = params[:zip_code] # Can be blank
zip_query = "AND zip_code = ?" unless zip_code.blank?
User.find(:all,
:conditions => ['first_name LIKE ? AND age=? AND country=? #{zip_query}',
"#{name}%", age, country, zip_code].reject(&:blank?)
Adding a reject(&:blank?) to the conditions arrays will filter the nil value.
Note: The other answers are much better if you are coding from zero, or refactoring.

How to access named_scope arguments from named scope extension?

following example:
named_scope :search, lambda {|my_args| {...}} do
def access_my_args
p "#{my_args}"
end
end
# Call:
Model.search(args).access_my_args
As you can see I want to access the arguments from the lambda in the named_scope extension. Is there a way to do this?
A more specific example:
class User < ActiveRecord::Base
named_scope :by_name, lambda {|name_from_scope| {:conditions => {:name => name_from_scope}}} do
def change_name
each { |i| i.update_attribute(:name, "#{name_from_scope}xyz") }
end
end
end
(I know that there is a find_by_name scope and so on...). I want to use the name_from_scope argument, that is passed in the scope in the scope extension.
named_scope :test_scope, lambda {|id| {:conditions => {:id => id}} } do
def test_scope_method
each {|i| puts #proxy_options.to_yaml}
end
end
I don't believe you can get to the arguments directly without extending activerecord.
#proxy_options will give you the compiled options in the block. So, in your example, you won't have access to name_from_scope but you will have access to #proxy_options[:conditions][:name].
Is this what you're trying to do?
named_scope :search, lambda {|*my_args|
OtherClass.announce_search_for_model(my_args, self.class)
{ :conditions => ['created_at < ?', my_args[:created_at]], :limit => my_args[:limit] }
}
args = {:created_at > 'NOW()', :limit => 5}
Model.search(args)
If you're wanting to observe what's passed onto the named_scope then I would do that in the lambda.
Named_scope results will always be a result as if you'd used Model.find. This is a functionality of rails so you need to override rails functionality with a Module if you want something different. I wouldn't recommend doing that because named_scope extensions are there for simplifying finders, not observing parameters.

Resources