2012-01-07 100 views
0

我试着设置一个表单验证,以确保至少1个和至多3个标签必须包含在窗体中。但它不起作用,因为仍然处理空的表单,但是具有4个逗号分隔标签的表单将得到正确验证。模型未验证

控制器

def update 
    @product = Product.find(params[:id]) 
    current_user.tag(@product, :with => params[:product][:tag_list], :on => :tags) 
    if @product.update_attributes(params[:product]) 
    redirect_to :root, :notice => "Added" 
    else 
    render :action => 'edit' 
    end 
end 

<%= form_for @product do |f| %> 
    <%= f.label :tag_list, "Your tags" %> <%= f.text_field :tag_list, :value => @product.tags_from(current_user) %> 
    <p><%= f.submit "Change" %></p> 
    <%= f.error_messages %> 
<% end %> 

模型

validate :required_info 
validates_size_of :tag_list, 
        :maximum => 3 

private 

    def required_info 
    if(tag_list.empty? and description.empty?) 
     errors.add_to_base "Add one" 
    end 
    end 

回答

0
if(tag_list.empty? and description.empty?) 
    errors.add_to_base "Add one" 
end 

只要看看模型的这部分,我想你宁愿做if(tag_list.empty? or description.empty?),因为你希望他们都被填充。

对于第二个确认,我不是一个act_as_taggable用户,所以我现在不能回答你。

+0

啊哈。它被设置为合乎逻辑的,因为描述被故意留空,但现在它不是,逻辑或者需要验证工作。感谢brainspark。 – Simpleton 2012-01-07 14:42:48

1

你可以使用一个自定义的验证:

validates :tag_list_length 

private 

def tag_list_length 
    errors.add(:tag_list, "Must include at least one and no more than three tags") unless tag_list.length.between?(1,3) 
end