Reputation: 245
I am searching the database for a unique key and I am getting it back but as an array I then have to take the first object and send that to my view
def watch
@video = Video.where("key = ?", params[:key])
@video = @video[0]
end
I feel like I am doing this the wrong way. Key is always unique so it will never return more than one object, I always want the first object. How can I make this one line?
Upvotes: 3
Views: 3966
Reputation: 573
On Rails <= 3.2.x you should use: @video = Video.find_by_key!(params[:key])
On Rails > 3.2.x you should use: @video = Video.find_by!(key: params[:key])
Those forms are preferred, because they raise ActiveRecord::RecordNotFound and the controller return the 404 HTTP code to the client.
http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html#method-i-find_by-21
Upvotes: 3
Reputation: 114248
You can use
@video = Video.find_by_key(params[:key])
Or
@video = Video.where(key: params[:key]).first
These return nil
if the key doesn't exist. If you prefer a ResourceNotFound
exception use the bang methods:
@video = Video.find_by_key!(params[:key])
Or
@video = Video.where(key: params[:key]).first!
Upvotes: 7