#
#= 子モデル対応コントローラー用モジュール
# Authors:: Sumiyo Yamamoto
# Copyright:: Copyright (C) OrbusNeich Medical K.K.  2010.
#--
# date        name                   note
# 2010.6.18   Sumiyo Yamamoto        新規作成
#-------------------------------------------------------------------------------
#++
module Comm::Module::Controller
  #= 子モデル対応コントローラー用モジュール
  #------------------------------------------------------------------------#++
  module Child
    def self.included(base)
      base.class_eval do
        before_filter :get_parent_id
        before_filter :get_table_params, :only => [:create_child]
        before_filter :edit_table_params, :only => [:create_child]
      end
    end

    #== 編集画面向け一件表示（親ID指定）
    #-----------------------------------------------------------------#++
    def child
      ar = find_child
      respond_to do |format|
        format.ext_json{
          json_data = ar ? (ar.to_ext_json) : ({:success => true, :data => ''})
          render :json => json_data
        }
      end
    end

    #== 登録（親ID指定）
    #-----------------------------------------------------------------#++
    def create_child
      ar = find_child
      # 既存データが存在する場合、更新
      if ar
        result = ar.update_mng(@table_params)
      # 存在しない場合、登録
      else
        ar = @mcls.new
        result = ar.create_mng(@table_params)
      end
      
      # 返却
      render :json => Comm::Tool::Json.result_json(result, ar.errmsg)
    end

  protected
    def get_parent_id
      @parent_id = params[:id].to_i
    end

    def edit_table_params
      @table_params[@parent_key] = @parent_id
    end

    def find_child
      return @mcls.sassign(@parent_key, @parent_id).first
    end
  end
end
