2012-01-07 99 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