:
class ResourcesController < ApplicationController
# Initialize resource and belonging type model
before_filter :build_resource_and_type, :only => [:new, :create]
before_filter :get_resource_and_type, :only => [:edit, :update]
def new
end
def create
if @resource.save
flash[:notice] = "Resource wurde erstellt"
redirect_to root_url
else
flash[:error] = "Resource konnte nicht erstellt werden"
render :action => 'new'
end
end
def edit
end
def update
if @resource.update_attributes(params[:resource])
flash[:notice] = "#{@type_name} #{@resource.title} wurde aktualisiert"
redirect_to root_url
else
flash[:error] = "#{@type_name} #{@resource.title} konnte nicht aktualisiert werden"
render :action => 'edit'
end
end
private
def build_resource_and_type
# Get type from URL param (new action) or hidden field param (create action)
type = params[:type_name] || params[:resource][:type_name]
@resource = current_user.microsite.resources.new(params[:resource])
@resource.type_name = type
# Build belonging model depending on type param
case type
when 'page'
@resource.build_page_setting(params[:page_setting])
@type_name = 'page'
end
end
def get_resource_and_type
@resource = current_user.microsite.resources.find(params[:id])
@type_name = @resource.type_name
end
end
そして、私のリソースフォームの重要な部分:ここで
class Resource < ActiveRecord::Base
has_one :page_setting
accepts_nested_attributes_for :page_setting
end
class PageSetting < ActiveRecord::Base
belongs_to :resource
end
は、リソースコントローラですあなたのリソースフォームに:
<%= f.fields_for :page_setting, @resource.page_setting do |page_form| %>
次に、あなたがしたいように動作するはずです。
@ resource.page_setting.update_attributes(params [:page_setting])を私の更新アクションに追加すると動作しますが、この "回避策"がなくても動作するはずですか? –