github
親bookが子commentを幾つか持つと設定。 特徴: *通常ネスト: 親の編集と子の編集は別々の画面で実行。これが一番簡単。 詳細 *パス設定は以下のようにネスト構造にする routes.rb
親bookが子commentを幾つか持つと設定。 特徴: *通常ネスト: 親の編集と子の編集は別々の画面で実行。これが一番簡単。 詳細 *パス設定は以下のようにネスト構造にする routes.rb
resources :book1s do
resources :comment1s do
end
end
*子のコントローラでの注意点
必ず親IDが渡ってくるので、アクションのが呼び出される前に
親オブジェクトを作っておく。サンプルではset_bookをコールしている
*form_forで:urlを設定する。オブジェクト名からコントローラ、
アクションを作ってくれない為。
以下のような感じ
<%= form_for(@book1,:url =>{:action => @nextaction}) do |f| %>
*モデルの設定belongs_toとhas_manyは正しく設定しておく
親側
class Book1 < ActiveRecord::Base
self.table_name = "books"
self.primary_key = "id"
has_many :comment1s ,:foreign_key => :book_id
end
子側
class Comment1 < ActiveRecord::Base
self.table_name = "comments"
self.primary_key = "id"
belongs_to :book,:foreign_key => "book_id"
end
*親子同時編集
親と子を同時に編集する方法。編集以外に新規追加、削除機能を編集画面に入れようとすると、javascript
でいろいろ各必要が有るため、面倒。
*パス設定 特に変更の必要はなし
resources :book2s
*親のcreate.updateに子の情報もparamsで渡ってくる為にparams情報にpermitを追加しておく必要がある。
それをしないと情報を書き込まない。特に小画面情報の:idは良く忘れるので、注意が必要
例:
def book2_params
params.require(:book2).permit(:title,:comment2s_attributes =>[:id,:content])
end
*コントローラーにaccepts_nested_attributes_forを設定する。
class Book2 < ActiveRecord::Base
self.table_name = "books"
self.primary_key = "id"
has_many :comment2s ,:foreign_key => :book_id
accepts_nested_attributes_for :comment2s
end
class Comment2 < ActiveRecord::Base
self.table_name = "comments"
self.primary_key = "id"
belongs_to :book,:foreign_key => "book_id"
end
*コントローラーnew
例:
@book2.comment2s.build
*ビューの変更
fields_forを使って小画面情報を親画面にで編集出来るようにする。
<%= f.fields_for :comment2s do |a| %>
<%= a.text_field :content %>
<% end %>
*複数情報の編集
複数情報を一括で編集。(子情報になっていない場合の複数編集)
これも追加、削除を同じ画面で行おうとするとjavascriptでいろいろ書く必要が有る為に、面倒
編集だけにとどめておいた方がいい
*コントローラー エラーの判定が上手く行かなかったので、少し通常とは違うようになっています
def update_all
@book3 = Book3.update(params[:book3].keys,params[:book3].values)
@isError = false
@book3.each{|book| @isError = true if book.errors.any?}
respond_to do |format|
if @isError == true
format.html { render action: "editall" }
format.json { render json: @book3.errors, status: :unprocessable_entity }
else
format.html { redirect_to :action=>:index, notice: 'Book was successfully updated.' }
format.json { head :no_content }
end
end
end
*ビュー form_forをつかってビューを作成しています
<%= form_tag :action => @nextaction do %>
<% @book3.each_with_index{|book,i| %>
<%= fields_for("book3[]",book) {|f| %>
<% } %>
<%= f.label :title %>
<% } %>
<%= f.text_field :title %> |
<%= submit_tag "送信" %>
<% end %>
