Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community!

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Ruby

RoR (Intermediate) Creating the friendship form. Why not use find! instead of where?

In the video the use the following to find a user by their profile name:

@friend = User.where(profile_name: params[:friend_id]).first

Thats all fine and dandy, the problem arises that you can pass invalid friend id's because where wont raise an ActiveRecord::RecordNotFound exception if the rows are empty. So they then suggest the following:

@friend = User.where(profile_name: params[:friend_id]).first
raise ActiveRecord::RecordNotFound if @friend.nil?

Why not use the find_by_x_and_x idiom? (I know its being taken out in Rails 4).

If you do:

@friend = User.find_by_profile_name(params[:friend_id])

The same issue happens, but find has a bang format that will raise an exception if nothing is returned. You could simply do:

@friend = User.find_by_profile_name!(params[:friend_id])

to get the same behaviour? Is there a reason why this isn't idiomatic, or why they didn't want to do it this way?

2 Answers

I also wondered this, I did use find methods in the end. Seemed much cleaner to me. I also wondered why they did the hover to display delete and edit bit with CoffeeScript instead of using a much simpler, modern, CSS3 :hover subclass.

I think this was done because the find methods are being depreciated in Rails4 http://edgeguides.rubyonrails.org/4_0_release_notes.html#active-record-deprecations (even though it seems like find_by_ survived)

where returns an ActiveRecord::Relation (not an array, even though it behaves much like one), which is a collection of model objects. If nothing matches the conditions, it simply returns an empty relation.

find (and its related dynamic find_by_columnname methods) returns a single model object, or possibly a collection of model objects in an Array (not a Relation). If nothing is found, an ActiveRecord::RecordNotFound exception is raised.

Thank you Nima, I know that ActiveRecord::Relation delegates array methods to the array class when its not defined (ActiveRecord::Relation.superclass == Array). I didn't know find didn't return an AR::Relation so it seems much more obvious to me now.

glad i could be a small help :)