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?
@video = Video.where("key =?" , params[:key]).first
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With