Reputation: 51
Actually, I have a little issue. I have a form where you can pick a name and so on. One is a text field, the other ones are select. I can change text field to required which means that you need to write something into it, but how can I do it with the other ones?
It's not a problem that I can add the user instead, but if I try to delete the user, I'm in trouble with this error:
Couldn't find Key with 'id'=
Extracted source (around line #51):
49 @student = Student.find(params[:id])
50 if @student
51 Key.find(@student.key_id).update(student_id: 0)
52 Harddrive.find(@student.harddrive_id).update(student_id: 0)
53 end
54 @student.destroy
And this is the code of my form:
<%= form_for @student, remote: true do |f| %>
<%= f.label 'Account' %>
<%= f.text_field :account, :class => "form-control form-control-text", :required => true %>
<br>
<%= f.label 'Operating system' %>
<%= f.select :os, '<option value="linux">Linux</option><option value="windows">Windows</option>'.html_safe,
{include_blank: false}, {:class => "form-control"} %>
<br>
<%= f.label 'Hard drive' %>
<%= f.select :harddrive_id, Harddrive.where(student_id: 0).map { |drive| [drive.name, drive.id] },
{include_blank: false}, {:class => "form-control"} %>
<br>
<%= f.label 'Key' %>
<%= f.select :key_id, Key.where(student_id: 0).map { |key| [key.name, key.id] }, {include_blank: false}, {:class => "form-control"} %>
<br>
<%= f.label 'Pawn' %>
<%= f.select :pawn, '<option value="true">Paid</option><option value="false">Not paid</option>'.html_safe,
{include_blank: false}, {:class => "form-control"} %>
<br>
<%= f.label 'Comment' %>
<%= f.text_field :comment, :class => "form-control form-control-text" %>
<br>
<%= f.submit (f.object.new_record? ? 'Create' : 'Update'), :class => "btn btn-outline-dark" %>
<% end %>
Cheers, absolado
Upvotes: 1
Views: 347
Reputation: 2004
To avoid exception, just modify code as follows:
@student = Student.find(params[:id])
if @student
Key.find(@student.key_id).update(student_id: 0) if @student.key_id.present?
Harddrive.find(@student.harddrive_id).update(student_id: 0)
end
@student.destroy
Or you can add required validation from model itself for key_id
class Student
validates :key_id, :presence => true
end
Upvotes: 2