James
James

Reputation: 245

Ruby on Rails Controller WHERE statement

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

Answers (3)

Américo Duarte
Américo Duarte

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

Stefan
Stefan

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

Vigrant
Vigrant

Reputation: 1008

@video = Video.where("key =?" , params[:key]).first

Upvotes: 8

Related Questions