Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
James Avatar asked Jun 09 '26 21:06

James


2 Answers

@video = Video.where("key =?" , params[:key]).first
like image 101
Vigrant Avatar answered Jun 11 '26 12:06

Vigrant


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!
like image 33
Stefan Avatar answered Jun 11 '26 11:06

Stefan