困ったときのメモ ver.2.0

主に Ruby on Rails のメモ。など。

Rails 3.1 で帳票フォームをつくるー

はじめに

親子関係のある帳票フォームは「accepts_nested_attributes_for」なかんじで比較的簡単だったので、調子にのって親子関係のないマスタ系の帳票フォームを作ったらハマったのでメモ。


ちなみにこれは 「 販売計画.heroku.com 」 で実装して、後にAjax化した。
なので危険なとこがあったら、教えてください。

モットーは 「 コードをできるだけ書かない 」

準備

おなじみのscaffoldで以下の内容を。

rails g scaffold product name:string price:decimal stock:integer

マスタ系の帳票フォーム(ふつうの)

とりあえず、追加と削除は後回しで更新のみできるフォームを作る。

帳票フォームと一括更新用のルーティングを追加
config/routes.rb

resources :products do
  get :edits, :on => :collection
  put :updates, :on => :collection
end

メソッド追加
app/controllers/products_controller.rb

def edits
  @products = Product.all
end

def updates
  @products = Product.all

  respond_to do |format|
    if Product.update(params[:product].keys, params[:product].values)
      format.html { redirect_to products_url, :notice => 'Product was successfully updated.' }
      format.json { head :ok }
    else
      format.html { render :action => "edits" }
      format.json { render :json => @products.errors, :status => :unprocessable_entity }
    end
  end
end

ビュー追加
app/views/products/edits.html.erb

<h1>Edits products</h1>

<%= form_tag({:action => :updates}, {:method => :put}) do %>
  <table>
    <tbody>
      <tr>
        <th>Name</th>
        <th>Price</th>
        <th>Stock</th>
      </tr>
  
      <% for @product in @products %>
        <tr>
          <td><%= text_field 'product[]', :name %></td>
          <td><%= text_field 'product[]', :price %></td>
          <td><%= text_field 'product[]', :stock %></td>
        </tr>
      <% end %>
    </tbody>
    <tfoot>
      <tr>
        <td colspan='4'><%= submit_tag %></td>
      </tr>
    </tfoot>
  </table>
<% end %>

<br />

<%= link_to 'Back', products_path %><br>

まとめ

「 form_tag 」 の書き方忘れてハマった。中カッコ必須。
なんか変な書き方っぽいけど、どうなんだろ。


〜〜form_tagが変な位置だったので修正。あとインデントも〜〜
〜〜いらんとこ削った〜〜
〜〜Ruby1.9.2に対応〜〜