マスター・ディティール系の保守画面の作り方

NewRelaseは検索条件が「見出し」+「複数の条件」と、一般的なマスター・ディティール形式になっている。そのため、まずはRailsでこれを実現するための方法をあれこれ検索。見つけたページがhttp://techno.hippy.jp/rorwiki/?HowToUpdateModelsWithHasManyRelationships、そのものズバリ。ラッキー。以下のような感じ。

edit.rhtml 抜粋

<% for @detail in @search_condition.searchConditionDetails %>
  <tr>
  <% for column in SearchConditionDetail.content_columns %>
    <td><%= text_field "detail[]", column.name %></td>
  <% end %>
  </tr>
<% end %>

search_conditions_controller.rb抜粋

  def update
    @search_condition = SearchCondition.find(params[:id])
    update_result = @search_condition.update_attributes(params[:search_condition])
    @search_condition.searchConditionDetails.collect do |detail|
      update_result &&= detail.update_attributes(@params[:detail][detail.id.to_s])
    end
    if update_result  
      flash[:notice] = 'SearchCondition was successfully updated.'
      redirect_to :action => 'show', :id => @search_condition
    else
      render :action => 'edit'
    end
  end

こんな感じで実に簡単にWebでマスター・ディティール系の保守画面が出来た。もうちょっと工夫すればAjaxで使い勝手の良い画面になるでしょう。が、それは後のお楽しみに。