Ruby On Rails:文本表单 - 如何将字段更改为必需?

时间:2018-03-26 11:17:14

标签: ruby-on-rails ruby

实际上,我有一点问题。我有一个表格,你可以选择一个名字,等等。一个是文本字段,其他是选择。我可以将文本字段更改为必需,这意味着您需要在其中写入内容,但我该如何与其他内容一起使用?

我可以添加用户不是问题,但如果我尝试删除用户,我就会遇到此错误:

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

这是我表格的代码:

<%= 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 %>

干杯, absolado

1 个答案:

答案 0 :(得分:2)

为避免异常,只需修改代码如下:

@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

或者您可以为key_id

添加模型本身所需的验证
class Student
  validates :key_id, :presence => true
end