我认为这是一个愚蠢的错误......当我创建一个记录时,我的“资源”和“page_settings”表格会被填充。
但是当我尝试更新记录时,我的“page_setting”没有任何作用。
我的模特:
class Resource < ActiveRecord::Base
has_one :page_setting
accepts_nested_attributes_for :page_setting
end
class PageSetting < ActiveRecord::Base
belongs_to :resource
end
这是资源控制器:
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
我的资源形式的基本部分:
<%= 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 %>
答案 0 :(得分:1)
您必须对资源表单进行一些小改动:
<%= f.fields_for :page_setting, @resource.page_setting do |page_form| %>
然后它应该像你想要的那样工作。