gpt4 book ai didi

ruby-on-rails - 在表单中设置 has_one 关系,但获取对象 vs 字符串异常

转载 作者:太空宇宙 更新时间:2023-11-03 16:07:04 24 4
gpt4 key购买 nike

我的模型中有一个 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'

为了更好的衡量,我的 Controller :

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

最佳答案

问题在于 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

关于ruby-on-rails - 在表单中设置 has_one 关系,但获取对象 vs 字符串异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11714504/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com