【问题标题】:Ruby on Rails - simple_form_for how to show error for each fieldRuby on Rails - simple_form_for 如何显示每个字段的错误
【发布时间】:2018-07-20 07:13:42
【问题描述】:

我想在我的每个字段下显示错误,我的 html.erb 如下:

<%= simple_form_for [:admin, @municipality, @subdomain], :html => {:class => ''} do |f| %>

    <%= f.input :subdomain, hint: 'Dominio senza senza http://', error: true%>

    <%= f.input :subdomain_type, as: :select, collection: [['Sito','S'],['Api','A']] %>
    <%= f.input :active %>
    <%= f.input :draft,
                hint: 'Si applica ai siti e indica se il sito è una bozza interna (e quindi non deve essere raggiungibile dai motori di ricerca)',
                label: 'È una bozza' %>
    <div class="form-actions">
      <%= f.button :submit, :class => 'btn-primary', :value => 'Salva' %>
      <%= link_to t('.cancel', :default => t("helpers.links.cancel")),
                  admin_municipality_subdomains_path, :class => 'btn' %>
    </div>
<% end %>

@subdomain 变量中,我有“errors”属性返回完整的错误列表,问题是:如何在子域字段下显示它?

编辑,控制器代码在这里:

class Admin::SubdomainsController < InheritedResources::Base
  layout 'admin'
  before_filter :authenticate_admin!
  before_filter :set_page_title
  load_and_authorize_resource
  actions :all, except: [:show]

  belongs_to :municipality
  add_breadcrumb Subdomain.model_name.human(:count => 2).titleize, :admin_municipality_subdomains_path

  def index
    @subdomain = Subdomain.new
    index!
  end

  def create
    create! {
      @municipality = Municipality.find(params[:municipality_id])
      admin_municipality_subdomains_path
    }
  end

  def destroy
    @municipality = Municipality.find(params[:municipality_id])
    @subdomain = Subdomain.find(params[:id])
    destroy!
  end

  private
  def permitted_params
    params.permit(:subdomain => [:active, :subdomain, :blocked, :subdomain_type, :draft])
  end

  def set_page_title
    @page_title = Subdomain.model_name.human(:count => 2).titleize
  end
end

【问题讨论】:

    标签: html ruby-on-rails error-handling simple-form-for


    【解决方案1】:

    我想你可以添加类似的东西

    <%= @subdomain.errors if @subdomain.errors %>
    

     <%= f.input :subdomain, hint: 'Dominio senza senza http://', error: true%>
    

    【讨论】:

    • 不,我想显示验证错误...例如,对于子域,我有validates :subdomain, :uniqueness =&gt; true,我想显示相对错误。
    • @Leonardo 嗯,我想我从来没有遇到过 simple_form 不显示错误消息(如果有的话)的情况。也许问题出在error: true 上?它有什么用?
    • 这只是一次尝试,即使没有错误也无法正确显示。
    • @Leonardo 检查@subdomain.errors 是否真的有任何错误,如果没有,我最好的猜测是你在控制器中搞砸了。你能提供控制器和型号代码吗?它可能与嵌套资源有关。
    • @subdomain.errors 有错误!但我无法显示它。我已经用控制器代码更新了问题。
    猜你喜欢
    • 2015-06-08
    • 1970-01-01
    • 1970-01-01
    • 2012-08-11
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多