【问题标题】:rails object expected got string in association预期的rails对象得到了关联的字符串
【发布时间】:2016-03-15 19:33:54
【问题描述】:

我有这个:

<%= f.association :gestor, selected: current_usuario.gestor_id, label_method: :descricao, value: current_usuario.gestor_id, disabled: true %>

我的控制器:

   def create
    @usuario = Usuario.new(usuario_params)
    respond_to do |format|
      if @usuario.save
        format.html { redirect_to controle_usuarios_path, notice: 'Usuario was successfully updated.' }
        format.json { render :index, status: :ok, location: @usuario }
      else
        format.html { render :new }
      end
    end
  end
(...)
    def usuario_params
          params.require(:usuario).permit(:cpf, :usuario_pai, :gestor_id, :email, :password, :password_confirmation, :agente_id, :perfil_id)
        end

和控制台:

Processing by ControleUsuariosController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xnMQOvRLO3cCrq/l5KSSG0qB3Pc8S4wtSgs4PTCTkaJ5kLLwMD73s/4TeBWYYbvmBKzvBca4T0eMT9F9UQo/Ew==", "usuario"=>{"usuario_pai"=>"admin@mail.com", "agente_id"=>"2", "cpf"=>"111.111.111-11", "email"=>"xxx@xxx.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "perfil_id"=>"2"}, "commit"=>"Criar Usuario"}

参数 gestor_id 没有出现,为什么?错误是这样的:

Usuario(#70271925151780) 预期,得到字符串(#3432540)

【问题讨论】:

  • 我猜你在参数中没有得到gestor_id,仅仅是因为选择框被设置为禁用(disabled =&gt; true 选项)。禁用的表单标签不会在表单提交时传递值。还是您稍后使用 Javascript 启用它?
  • 哇,我删除了 disabled: true,并提交了参数 gestor_id,但我得到了同样的错误: Usuario(#48266120) expected, got String(#6291560) =/
  • 所以我猜这是两个不相关的错误(缺少属性和您描述的错误)。缺少的属性已经解决(通过再次启用选择),但要更正另一个错误,我们需要您将我们指向代码中确切发生错误的行。
  • 错误就在 def create @usuario = Usuario.new(usuario_params)
  • 你能从错误堆栈跟踪中再发布几行吗?

标签: ruby-on-rails ruby-on-rails-4 associations


【解决方案1】:

Rails 正在寻找 gester_id 并且您将 gester 作为参数传递,因此它正在被删除。尝试在您的视图中将其更改为 gester_id 或在您的参数过滤器中更改为 gester

【讨论】:

  • 但我没有 gestor_id,我只有 gestor。在我的专栏中,在我的表格中,在我的参数中。我试了一下,得到了这个错误:未找到关联
  • @EltonSantos 看起来您正在返回 current_usuario.gestor_id,您能展示一下您的表格吗?
  • Usuario 表是:cpf 字符变化(14)、gestor_id 整数、usuario_pai 整数、admin boolean、agente_id 整数、perfil_id 整数。 Gestor表是:id和descricao。用户属于_to gestor,Gestor has_many usuarios
猜你喜欢
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-17
  • 1970-01-01
  • 2023-03-31
  • 1970-01-01
相关资源
最近更新 更多