2

我的模型中有一个 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 #,而不实际更改关联的表单。我错过了什么?

4

1 回答 1

2

问题是 params[:organization][:template] 的值是包含所选模板 ID 的字符串。您需要使用该 ID 查找 Template 的实际实例并分配给 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
于 2012-07-30T03:12:10.167 回答