开发者

How do I add validation to a partial in Rails 3?

This is the error I am getting:

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>

My client model looks like this:

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

This is how the app/views/client/_form.html.erb partial looks:

  <%# 
  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_f开发者_JAVA技巧or(: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 %>

How do I fix that error ?


The problem is caused by the following line in your model:

validates :number_of_clients

When you use validates (s in the end) you have to follow the default rails validations like you did with the name validation. However, when you use a custom method to do the validation, you should use validate instead. So this should work:

validate :number_of_clients
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜