ben3019201
ben3019201

Reputation: 391

Convert Rails Active Record query 'find' method to 'where' method

How do I convert this find query method below to use the where method instead (just trying to better myself in rails)?

@deals = Deal.find(params[:id])

I've tried

@deals = Deal.where(deal_id: params[:id])

AND

@deals = Deal.where("deal_id = params[:id]")

But am not getting any results -- I'm receiving undefined method errors and an assortment of other errors. Any help?

Thanks

Upvotes: 0

Views: 201

Answers (3)

Denis
Denis

Reputation: 222

@deal = Deal.find(params[:id])

equivalent

@deal = Deal.where(id: params[:id]).first

.find() will return an exception if record not exist.

.where().first will return nil if record not exist.

Upvotes: 1

Hugo
Hugo

Reputation: 2129

The safe approach is:

@deals = Deal.where("deal_id = ?", params[:id])

Upvotes: 2

DustinFisher
DustinFisher

Reputation: 396

You would make your query like so:

@deal = Deal.where(id: params[:id])

Upvotes: 1

Related Questions