使用acts_as_taggable_on,我怎样才能拥有最大数量的标签?
问问题
744 次
1 回答
4
我在我的 Post 模型中使用以下验证
class Post < ActiveRecord::Base
...
acts_as_taggable_on :categories
...
validates_presence_of :category_list,
:message => "Choose at least 1 category"
validates_size_of :category_list,
:maximum => 4,
:message => '4 categories maximum'
...
end
正如 Ryan Bate 的教程中所见:
class PostssController < ApplicationController
..
def update
@post = current_user.posts.find(params[:id])
params[:post][:category_list] ||= []
end
..
end
类别选择部分:
<% Category.roots.each do |c| %>
<ul>
<li>
<%= check_box_tag "post[category_list][]",
c.id, @post.category_list.include?(c.id.to_s)%>
<%= c.name %>
</li>
</ul>
<% end %>
顺便说一句,我使用 catgeory_list 作为类别 ID 的数组,因此 Post category_list 可能如下所示:
> p = Post.first
...
> p.category_list
["10", "7", "8"]
> p.category_list.map { |c| Category.find(c.to_i).name }
["Cats","Dogs","Plants"]
希望能帮助到你
于 2011-04-26T17:13:54.700 回答