#2
Mar 07
Dynamic find_by Methods
Shorten simple finds considerably and improve readability by using the dynamic find_all_by and find_by methods.
# tasks_controller.rb def incomplete @tasks = Task.find_all_by_complete(false) end def last_incomplete @task = Task.find_by_complete(false, :order => 'created_at DESC') end




hola
wohoo, now i can shorten my code more, thx for the tip
Hi, I saw this railscast a while back and I've been meaning to ask something.
I like the dynamic find_by methods, but don't you lose the protection you get by the use of the question mark followed by variables?
Is "Task.find_all_complete(false)" less secure than "Task.find(:all, :conditions => ['complete = ?', false])" ? For example, if we were to plug a user-supplied value as the argument tot he dynamic find_by methods?
@Enrique, good question. Thankfully Rails automatically quotes and escapes the input variable for the dynamic find by methods, so it is just as secure as using the full conditional statement with the question mark.
Ror is full of good things to help us on doing quick stuff
Hi , This will be so usefull.Thank u so much.
I wanted to reference the documentation because it took me quite a while to find this. http://api.rubyonrails.org/classes/ActiveRecord/Base.html#M001024
That's all about the with_scope method in ActiveRecord::Base. Hopefully someone else finds it useful for me to link it here.
Hi,
Is there a way of using find_all_by type methods to replace conditions with wildcards in using LIKE or REGEXP?
Thanks very much for your help
@Helena, you'll have to use a full find for that:
Task.find(:all, :conditions => ['name LIKE ?', name])
The shortcut find_by methods only work with equals comparison.
Perhaps it would also be worth mentioning that you can combine conditions like this:
Task.find_all_by_complete_and_category_id(false, 1)