未将验证错误传递给父

时间:2017-12-15 15:04:22

标签: ruby-on-rails ruby activerecord

我目前正在构建一个Rails应用程序,我有两个相关的模型 子网和设备,设备都在子网内。两者都做了一定程度的验证。

class Subnet < ApplicationRecord
  has_many :devices , dependent: :destroy

  validates_presence_of :devices

  validates :name, presence: true, uniqueness: true
  validates :CIDR, presence: true
  validates_associated :devices
end



class Device < ApplicationRecord
  belongs_to :subnet

  validates :subnet, :presence => true

  validates :name, presence: true, uniqueness: {scope: :subnet_id}
  validates :IP, presence: true, uniqueness: {scope: :subnet_id}
 end

当尝试创建一个已经存在的新设备时,将不会创建这个新设备 - 这应该是这样的。 虽然,我希望在此事件后显示某种错误消息,但我的代码似乎没有将错误从子项移交给父项。
我对子网的看法的相关部分(也包含错误处理)如下所示:

...
<% if @subnet.errors.any? %>     <-------- This line seems to not get the information about the failed validation of the device
  <div id="error_explanation">
    <h2>
      <%= pluralize(@subnet.errors.count, "error") %> prohibited
      this subnet from being saved:
    </h2>
    <ul>
      <% @subnet.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
    </ul>
  </div>
<% end %>

<h2>Add a device:</h2>
<%= form_with(model: [ @subnet, @subnet.devices.build ], local: true) do |form| %>
  <p>
    <%= form.label :name %><br>
    <%= form.text_field :name %>
  </p>
  <p>
    <%= form.label :IP %><br>
    <%= form.text_field :IP %>
  </p>
  <p>
    <%= form.label :notes %><br>
    <%= form.text_area :notes %>
  </p>
  <p>
    <%= form.submit %>
  </p>
<% end %>  
...

来自device_controller的设备的create函数如下所示:

def create
    @subnet = Subnet.find(params[:subnet_id])
    @device = @subnet.devices.create(device_params)
    redirect_to subnet_path(@subnet)
end  

如何让subnet show view对来自设备的错误作出反应?

0 个答案:

没有答案