rails3で複数レコード修正は少しコードを書くと問題無く出来るですが、検証機能を使った後の赤枠(デフォルト)が出なく、困っていました。いろいろ試して出来たので、メモとして残しておきます。
エラー内容とエラー箇所が赤枠で表示されています。
books_controller.rb
エラー内容とエラー箇所が赤枠で表示されています。
def editall
@book = Book.all
end
def updates
@book = Book.update(params[:book].keys,params[:book].values)
@isError = false
@book.each{|book| @isError = true if book.errors.any?}
respond_to do |format|
if @isError == true
format.html { render action: "editall" }
format.json { render json: @book.errors, status: :unprocessable_entity }
else
format.html { redirect_to :action=>:index, notice: 'Book was successfully updated.' }
format.json { head :no_content }
end
end
end
ポイント:updateで一気に検証と修正してくれます。検証でエラーが発生している場合はupdateはされません。
eitall.html.erb
Editing book
<% if @isError == true then %><% end %> <%= form_tag :action => :updates do %><%#= pluralize(book.errors.count, "error") %> prohibited this book from being saved:
<% @book.each_with_index{|book,i| %> <% if book.errors.any? %> <% book.errors.full_messages.each do |msg| %>
- <%= "#{i+1}line: #{msg}" %>
<% end %> <% end %> <% } %>
| <%= f.text_field :title %> | <%= f.text_field :price %> | <%= f.text_field :content %> | <% } %>
"book"=>{"1"=>{"title"=>"rails", "price"=>"1", "content"=>""}, "2"=>{"title"=>"railsによるWeb", "price"=>"1000", "content"=>""}}
book.rb
class Book < ActiveRecord::Base
validates(:price,:numericality => {:greater_than => 10})
validates(:title,:length =>{:within => 1..5})
end
routes.rb
get 'books/editall' post 'books/updates' resources :booksソースコード

0 件のコメント:
コメントを投稿