【发布时间】:2011-01-23 14:53:37
【问题描述】:
我认为这是一个愚蠢的错误……当我创建记录时,我的“resources”和“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 %>
【问题讨论】:
-
当我将 @resource.page_setting.update_attributes(params[:page_setting]) 添加到我的更新操作中时,它可以工作......但我认为如果没有这个“解决方法”它应该可以工作?
标签: ruby-on-rails-3 associations