如何在Rails 3中为部分添加验证?

时间:2011-02-15 23:21:41

标签: validation ruby-on-rails-3

这是我得到的错误:

ArgumentError in Home#index

Showing /app/views/clients/_form.html.erb where line #6 raised:

You need to supply at least one validation
Extracted source (around line #6):

3:   render :partial => "clients/form", 
4:          :locals => {:client => client}
5: -%>
6: <% client ||= Client.new 
7:    new_client = client.new_record? %>
8: <%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
9:  <div class="validation-error" style="display:none"></div>

我的客户端模型如下所示:

class Client < ActiveRecord::Base
  # the user model for the client
  belongs_to :user

  has_many :projects, :order => 'created_at DESC', :dependent => :destroy

  #The following produces the designers for a particular client.
  #Get them from the relations where the current user is a client.
  has_one :ownership, :dependent => :destroy

  has_one :designer, :through => :ownership


  validates :name, :presence => true,
                   :length => {:minimum => 1, :maximum => 128}

  validates :number_of_clients

  def number_of_clients
     Authorization.current_user.clients.count <= Authorization.current_user.plan.num_of_clients    
  end

end

app/views/client/_form.html.erb部分看起来是这样的:

  <%# 
  Edit a single client
  render :partial => "clients/form", 
         :locals => {:client => client}
-%>
<% client ||= Client.new 
   new_client = client.new_record? %>
<%= form_for(client, :html => { :class=>"ajax-form", :id => "client-ajax-form"}, :remote => true, :disable_with => (new_client ? "Adding..." : "Saving...")) do |f| %>
    <div class="validation-error" style="display:none"></div>
      <div>
        <label for="client_name"><span class="icon name-icon"> </span></label>
        <input type="text" class="name" size="20" name="client[name]" id="client_name" value="<%=  client.name %>" >    <%= f.submit(new_client ? "Add" : "Save", :class=> "green awesome")%>
    </div>
<% end %>
<% content_for(:deferred_js) do %>
// From the Client Form
$('#client-ajax-form')
    .bind("ajax:success", function(evt, data, status, xhr){
    console.log("Calling Step View");
    compv.updateStepView('client', xhr);
});
<% end %>

如何修复该错误?

1 个答案:

答案 0 :(得分:5)

问题是由模型中的以下行引起的:

validates :number_of_clients

当您使用validates(最后的s)时,您必须遵循默认的rails验证,就像您使用名称验证一样。但是,当您使用自定义方法进行验证时,应该使用validate。所以这应该有效:

validate :number_of_clients