创建模型对象时,为什么会出现AssociationTypeMismatch? [英] Why do I get a AssociationTypeMismatch when creating my model object?

查看:150
本文介绍了创建模型对象时,为什么会出现AssociationTypeMismatch?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

ActiveRecord::AssociationTypeMismatch in ContractsController#create

ExchangeRate(#2183081860) expected, got HashWithIndifferentAccess(#2159586480)

Params:
{"commit"=>"Create",
 "authenticity_token"=>"g2/Vm2pTcDGk6uRas+aTgpiQiGDY8lsc3UoL8iE+7+E=",
 "contract"=>{"side"=>"BUY",
 "currency_id"=>"488525179",
 "amount"=>"1000",
 "user_id"=>"633107804",
 "exchange_rate"=>{"rate"=>"1.7"}}}

我的相关模型是:

class Contract < ActiveRecord::Base
  belongs_to :currency
  belongs_to :user
  has_one :exchange_rate
  has_many :trades

  accepts_nested_attributes_for :exchange_rate
end

class ExchangeRate < ActiveRecord::Base
  belongs_to :denccy, :class_name=>"Currency"
  belongs_to :numccy, :class_name=>"Currency"
  belongs_to :contract
end

我的看法是:

<% form_for @contract do |contractForm| %>


    Username: <%= contractForm.collection_select(:user_id, User.all, :id, :username) %> <br>


    B/S: <%= contractForm.select(:side,options_for_select([['BUY', 'BUY'], ['SELL', 'SELL']], 'BUY')) %> <br>


    Currency: <%= contractForm.collection_select(:currency_id, Currency.all, :id, :ccy) %> <br> <br>


    Amount: <%= contractForm.text_field :amount %> <br>

    <% contractForm.fields_for @contract.exchange_rate do |rateForm|%>
        Rate: <%= rateForm.text_field :rate %> <br>
    <% end %>

    <%= submit_tag :Create %>

<% end %>

我的视图控制器:

class ContractsController < ApplicationController

  def new
    @contract = Contract.new
    @contract.build_exchange_rate


    respond_to do |format|
      format.html # new.html.erb
      format.xml  { render :xml => @contract }
    end

  end

  def create
    @contract = Contract.new(params[:contract])

    respond_to do |format|
      if @contract.save
        flash[:notice] = 'Contract was successfully created.'
        format.html { redirect_to(@contract) }
        format.xml  { render :xml => @contract, :status => :created, :location => @contract }
      else
        format.html { render :action => "new" }
        format.xml  { render :xml => @contract.errors, :status => :unprocessable_entity }
      end
    end
  end

我不确定为什么无法识别汇率属性?

I'm not sure why it's not recognizing the exchange rate attributes?

谢谢

推荐答案

问题是accepts_nested_attributes_for :exchange_rate在参数中查找"exchange_rate_attributes",而不是"exchange_rate". fields_for助手将为您完成此操作,但是您必须将其更改为:

The problem is that accepts_nested_attributes_for :exchange_rate looks for "exchange_rate_attributes" in the params, not "exchange_rate". The fields_for helper will do this for you, but you have to change it to:

<% contractForm.fields_for :exchange_rate do |rateForm|%>

这篇关于创建模型对象时,为什么会出现AssociationTypeMismatch?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆