ActiveScaffoldの続き
本家のドキュメントを読んだりしながら、試行錯誤の末に編集画面も出来ました。
変更画面
タグの編集ですが、tagsのform_ui を :select に設定するとタグ毎の checkbox が出てくるようになりました。
しかし、更新しても タグの関連情報は taggingテーブルにあるので変更されません (ActiveRecordの多対多サポート機能上の制限かな?)。そこで、自分で customerテーブル変更後に tagging テーブルを更新するようにしました。
class CustomersController < ApplicationController active_scaffold :customer do |config| config.list.per_page = 10 config.list.sorting = {:id => :asc} config.label = "顧客データ" config.columns = [:id, :name, :company, :email, :tags, :created_at] config.columns[:name].label = "名前" config.columns[:company].label = "会社" config.columns[:created_at].label = "登録日" config.columns[:updated_at].label = "更新日" config.columns[:tags].label = "タグ" config.columns[:name].required = true config.columns[:email].required = true config.columns[:tags].form_ui = :select config.show.columns = [:id, :name, :company, :email, :tags, :created_at, :updated_at] config.update.columns = [:name, :company, :email, :tags, :created_at, :updated_at] config.create.columns = [:name, :company, :email, :tags] end protected def after_update_save(record) record.update_tags(tag_id_param_list()) end def after_create_save(record) record.update_tags(tag_id_param_list()) end def tag_id_param_list h = params[:record][:tags] h ? h.values.map{|r| r["id"].to_i} : [] end end
class Customer < ActiveRecord::Base has_many :taggings has_many :tags, :through => :taggings def update_tags(tags) Tagging.transaction do Tagging.delete_all(["customer_id = ?", id]) tags.each do |tag_id| Tagging.new({:customer_id=> id, :tag_id=> tag_id}).save!() end end end end
ちなみに、after_update_saveメソッドに付いては、本家のドキュメントには書いてありませんでしたが CHANGESファイルに書いてありました。
それから、日付を日本風にするのは helper で行いました。
module CustomersHelper def created_at_column(record) record[:created_at] ? record[:created_at].strftime("%Y/%m/%d") : "" end def created_at_form_column(record, name) date_select(:record, :created_at, :name => name, :order=>[:year,:month,:day], :use_month_numbers=>true, :start_year=>2000) end def updated_at_column(record) record[:updated_at] ? record[:updated_at].strftime("%Y/%m/%d") : "" end def updated_at_form_column(record, name) date_select(:record, :updated_at, :name => name, :order=>[:year,:month,:day], :use_month_numbers=>true, :start_year=>2000) end end
もう少し直したいところもありますが、これで使えるレベルになりました ^^)/