我的模型中有一个has_one关系(组织有一个模板),我正在尝试通过表单更新它。但是,当我这样做时,我收到以下错误:
ActiveRecord::AssociationTypeMismatch in OrganizationsController#update
Template(#70209323427700) expected, got String(#70209318932860)
这有点复杂,因为每个组织都有许多与之关联的模板,但只有一个当前模板,如模型所示:
class Organization < ActiveRecord::Base
validates :subdomain, :presence => true, :uniqueness => true
validates :current_template, :presence => true
has_many :organization_assignments
has_many :people
has_many :pages
has_many :templates
has_many :users, :through => :organization_assignments
has_one :current_template, :class_name => 'Template'
attr_accessible :name, :subdomain, :template_id, :current_template, :current_template_id
end
这是我的表格:
= simple_form_for @organization, :html => { :class => 'form-horizontal' } do |f|
- @organization.errors.full_messages.each do |msg|
.alert.alert-error
%h3
= pluralize(@organization.errors.count, 'error')
prohibited this organization from being saved:
%ul
%li
= msg
= f.input :name
= f.input :subdomain
= f.input :current_template, :collection => @organization.templates, :selected => @organization.current_template
.form-actions
= f.submit nil, :class => 'btn btn-primary'
= link_to t('.cancel', :default => t("helpers.links.cancel")), organizations_path, :class => 'btn'
好的方法,我的控制器:
def update
@organization = Organization.find(params[:id])
respond_to do |format|
if @organization.update_attributes(params[:organization])
format.html { redirect_to @organization, notice: 'Organization was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @organization.errors, status: :unprocessable_entity }
end
end
end
我尝试过使用嵌套表单:
= simple_fields_for :current_template do |f|
= f.input :current_template, :collection => @organization.templates, :selected => @organization.current_template
但是所有成功的做法都是更改ID#,而不是实际更改关联的表单。我错过了什么?
答案 0 :(得分:2)
问题是params [:organization] [:template]的值是包含所选模板ID的字符串。您需要使用该ID查找模板的实际实例,并分配给params [:organization] [:template]。例如:
def update
@organization = Organization.find(params[:id])
if (params[:organization])
params[:organization][:template] = Template.find(params[:organization].delete(:template))
end
respond_to do |format|
if @organization.update_attributes(params[:organization])
# ...
end
end