大家下午好。
我有一个自定义验证来检查字数,但我想知道是否有一种方法可以隐藏视图中的内容,具体取决于验证通过/失败。
这是我到目前为止所做的:
_
form.html.erb
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= @book.title %>
</p>
<p>
<strong>Type:</strong>
<%= @book.size %>
</p>
<div id="snippets">
<%= render :partial => @book.snippets %>
</div>
<% if size_limit = true %>
<h2>Comments Closed</h2>
<% else %>
<%= form_for [@book, @snippet] do |f| %>
<p>
<%= f.label :title, "New comment" %><br/>
<%= f.text_area :content %>
</p>
<p><%= f.submit "Create Snippet" %></p>
<% end %>
<% end %>
<%= link_to 'Edit', edit_book_path(@book) %> |
<%= link_to 'Back', books_path %>
我需要在控制器中定义一些内容吗?
修订后的代码 - 无法使用
<% if @book.snippet.errors.blank? %>
<%= form_for [@book, @snippet] do |f| %>
<p>
<%= f.label :title, "New comment" %><br/>
<%= f.text_area :content %>
</p>
<p><%= f.submit "Create Snippet" %></p>
<% end %>
<% else %>
<h2>Comments Closed</h2>
<% end %>
<%= link_to 'Edit', edit_book_path(@book) %> |
<%= link_to 'Back', books_path %>
自定义验证:
validate :size_limit
BOOK_SIZE = {
0 => {"per" => 50, "total" => 50},
1 => {"per" => 6 , "total" => 60},
2 => {"per" => 7, "total" => 70}
}
def size_limit
book_limit = self.book.size
word_count = self.content.scan(/\w+/).size
current_snippets_size = (self.book.get_word_count || 0) + word_count
errors.add(:content, "Content size is too big") unless word_count < BOOK_SIZE[book_limit]['per'] && current_snippets_size < BOOK_SIZE[book_limit]['total']
end
错误测试:
irb(main):022:0> b = Book.last
←[1m←[36mBook Load (0.0ms)←[0m ←[1mSELECT "books".* FROM "books" ORDER BY "books"."id" DESC LIMIT 1←[0m
=> #<Book id: 14, title: "AAAA", size: 0, created_at: "2013-10-21 10:49:07", updated_at: "2013-10-21 10:49:07", approved: false, t
otal: nil, cat: "Sci-Fi">
irb(main):023:0> snip = b.snippets.create({:content => "Hell"})
←[1m←[35m (0.0ms)←[0m begin transaction
←[1m←[36mBook Load (0.0ms)←[0m ←[1mSELECT "books".* FROM "books" WHERE "books"."id" = ? ORDER BY "books"."id" ASC LIMIT 1←[0m
[["id", 14]]
←[1m←[35mSnippet Load (0.0ms)←[0m SELECT "snippets".* FROM "snippets" WHERE "snippets"."book_id" = ? [["book_id", 14]]
←[1m←[36m (0.0ms)←[0m ←[1mcommit transaction←[0m
=> #<Snippet id: nil, content: "Hell", book_id: 14, approved: nil, created_at: nil, updated_at: nil>
irb(main):024:0> snip.valid?
=> false
irb(main):025:0> snip.errors.blank?
=> false
irb(main):026:0> snip.errors
=> #<ActiveModel::Errors:0x5aada18 @base=#<Snippet id: nil, content: "Hell", book_id: 14, approved: nil, created_at: nil, updated_
at: nil>, @messages={:content=>["Content size is too big"]}>
答案 0 :(得分:0)
验证失败后要隐藏哪一部分视图?