【问题标题】:Rails / Formtastic - Validation isn't occuringRails / Formtastic - 验证没有发生
【发布时间】:2011-06-11 15:48:10
【问题描述】:

我正在使用 formtastic 来验证表单:

<%= semantic_form_for @user do |f| %>
  <ul class="formItem">         
    <%= f.input :username, :required => true, :label => "Your Username", :input_html => { :class => 'double' } %><br clear="all" />
    <p class="fieldExplanation">Your username is made public to other people on the site.</p>                       
  </ul> 
  <ul class="actions">      
    <%= f.commit_button("Save my profile and make a match >", :class => "submitForm") %>    
  </ul>
<% end %>

它在视觉上是有效的 - 表单带有一个小星号,表示它理解 :required => true - 但是当页面发布时,它不会触发错误验证;相反,它只是移动到下一页,就好像它成功了一样。

我觉得我在某处缺少一个简单的设置来打开验证,或者我的控制器做错了什么?

def update
 @user = User.find(params[:id])     
 respond_to do |format|
   if @user.update_attributes(params[:user])        
      format.html { redirect_to(match_user_path(@user), :notice => 'User was successfully updated.') }              
   else
     format.html { render :action => "edit" }        
   end
 end
end

提前致谢。

【问题讨论】:

  • 我开始认为还有其他问题 - 当我包含 &lt;%= f.input :mySelectBox, as =&gt; :select, :collection =&gt; ["Thing one", "Thing two"] %&gt; 时,我得到 undefined local variable or method `as' for #:0x837a368>

标签: ruby-on-rails ruby validation formtastic


【解决方案1】:

您在评论中显示的代码中省略了冒号。它应该是:as,这可以解释一些破损。

就验证而言,这是在您的模型中强制执行的。你需要这样的东西:

validates :username, :presence => true

让服务端的代码明白,没有username,模型无效。完成所有服务器端验证后,如果您想快速将这些验证转换为表单,请查看 validation_reflections gem。你可以阅读它on ASCIIcasts here

【讨论】:

    【解决方案2】:

    Formtastic 是表单的呈现,因此验证需要在模型的服务器端完成。 Formtastic 将使用这些验证来推断输入是否应标记为必需。 DSL 中的 :required 选项实际上只是为了覆盖它,用于在模型验证中无法执行所需操作的极少数情况下。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-01-14
      • 1970-01-01
      相关资源
      最近更新 更多