Please read for an updated status on RailsCasts:
Learn more or hide this
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.
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.
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:
You can find more about this here: http://api.rubyonrails.org/classes/ActiveRecord/Base.html
Under "Dynamic attribute-based finders"
What does the "False" do? Thanks.
Now it's possible to write an even better version of last_incomplete:
@task = Task.find_last_by_complete(false)
Exactly, @elomarns, but in this case we get ORDER BY 'id', not ORDER BY 'created_at' or another special column.
You're sure, but to sort by id or created_at retrieves the same record on this case. And it's better to sort by an integer column than by a date column, for performance reasons.
Is this railscast still relevant?
I read that I need to use find(:all) now for 3.1
Beware, cause this is now deprecated: Rails 4 release notes
For any beginner like me, I would like to say that multiple fields and all_by dynamic finders have been removed. However single field ones are still usable.
find_by_email will work
find_all_by_gender will not work
find_last_by_status will not work
This episode has been updated to Rails 4.2.5 Dynamic Attribute Based Finders in Rails 4.2
Does anybody know what the difference between find_by and find_by_all is?
First sign in through GitHub to post a comment.