Why do I get a AssociationTypeMismatch when creating my model object?

Posted by Maxm007 on Stack Overflow See other posts from Stack Overflow or by Maxm007
Published on 2010-04-18T17:16:17Z Indexed on 2010/04/18 17:23 UTC
Read the original article Hit count: 383

Filed under:
|

Hi

I get the following error:

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"}}}

My relevant model is :

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

My view is:

<% 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 %>

My View Controller:

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?

Thank you

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about nested-forms