1
我想设置一个验证,以便人们不能提交帖子,除非他们点击该帖子的类别,还要确保他们只能选择该帖子的其中一个分类所以帖子只能有一个类别。下面是modles使用验证与has_many_through
class Categorization < ActiveRecord::Base
belongs_to :post
belongs_to :category
end
class Category < ActiveRecord::Base
has_many :categorizations
has_many :posts, :through => :categorizations
end
class Comment < ActiveRecord::Base
belongs_to :user
validates :content, presence: true,
length: { minimum: 5 }
end
class Post < ActiveRecord::Base
belongs_to :user
has_many :comments
has_many :categorizations
has_many :categories, :through => :categorizations
validates :title, :content, presence: true,
length: { minimum: 5, maximum: 140 }
end
也在这里是我的形式:
<%= form_for @post, :html => {:multipart => true} do |f| %>
<% if @post.errors.any? %>
<div id="error_explanation" class="animated tada">
<h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
<ul>
<% @post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.file_field :image %>
</div>
<div class="field">
<%= f.label :content %><br>
<%= f.text_area :content %>
</div>
<%= hidden_field_tag "post[category_ids][]", nil%>
<% Category.all.each do |category| %><br>
<%= check_box_tag "post[category_ids][]", category.id, @post.category_ids.include?(category.id), id: dom_id(category)%>
<%= label_tag dom_id(category), category.name %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
</div>
做任何你知道什么,我需要投入,使我的形式带回来一个消息,说需要选择类别或者只能选择一个类别?