Reputation: 44310
I have a model with these fields:
Department:
name:string
deptid:integer
I've run rake db:migrate
and have seeded the table with 5 records. In the departments controller, I have:
def show
@dept = Department.find(params[:deptid])
end
In show.html.erb:
<%= @dept.name %>
In routes.rb
get 'departments/:deptid' => 'departments#show'
When I do this localhost:3000/show/2, I get the second record. If I instead use localhost:3000/show/212, where deptid=212 is valid, I get a
Couldn't find Department with 'id' = 212
error. Since I have specified deptid and not id (primary key), why does it still look for the PK?
Upvotes: 2
Views: 53
Reputation: 25029
The find
method will always look up a record by its primary key - in this case, you have not changed the primary key, so it is trying to look up records by id
.
If you want to look up a single record by a different field, you can use find_by
(or find_by!
, the difference being that find_by!
will raise an exception if no record is found, just like find
does). In this case, you probably want:
Department.find_by!(deptid: params[:deptid])
Upvotes: 3