开发者

with acts_as_taggable_on, how can I have a maximum number of tags?

开发者 https://www.devze.com 2023-02-28 17:22 出处:网络
with act开发者_如何学JAVAs_as_taggable_on, how can I have a maximum number of tags?I use the following validations in my Post model

with act开发者_如何学JAVAs_as_taggable_on, how can I have a maximum number of tags?


I use the following validations in my Post model

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

As seen in Ryan Bate's tutorial:

class PostssController < ApplicationController
  ..
  def update
    @post = current_user.posts.find(params[:id])
    params[:post][:category_list] ||= []
  end
  ..
end

Categories select partial:

<% 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 %>

BTW, I use catgeory_list as an array of categories ID's, so a Post category_list may look like:

> p = Post.first
...
> p.category_list
["10", "7", "8"]
> p.category_list.map { |c| Category.find(c.to_i).name }
["Cats","Dogs","Plants"]

Hope it helps

0

精彩评论

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

关注公众号