I think this is a stupid mistake… When i create a record, my "resources" and "page_settings" tables getting populated.
But my "page_setting" does nothing when i try to update the record.
My models:
class Resource < ActiveRecord::Base
has_one :page_setting
accepts_nested_attributes_for :page_setting
end
class PageSetting < ActiveRecord::Base
belongs_to :resource
end
Here is the resources controller:
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[:notic开发者_JS百科e] = "#{@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
And the essential part of my resource form:
<%= form_for @resource do |resource_form| %>
<%= resource_form.hidden_field :type_name, :value => @type_name %>
…
<%= fields_for @resource.page_setting do |page_form| %>
<%= page_form.label :content, "Text" %>
<%= page_form.text_area :content %>
<% end %>
<% end %>
You have to make a small change in Your resource form:
<%= f.fields_for :page_setting, @resource.page_setting do |page_form| %>
Then it should work, like You want to.
精彩评论