calyxofheld
calyxofheld

Reputation: 2148

what is causing this AssociationTypeMismatch in my controllers?

I have two controllers - ItemsController and TradesController. I'm building a @trade inside the ItemsController #show action, which is sent to the TradesController #create action with a form.

class ItemsController < ApplicationController
 def show
  @item = Item.friendly.find(params[:id])
  @trade = current_user.requested_trades.build
  @approved_trades = @item.trades
  respond_to do |format|
   format.html
   format.json { render :json => @items.to_json(:methods => [:image_url]) }
  end
end

class TradesController < ApplicationController
 def create
  @trade = current_user.requested_trades.build(trade_params)
  respond_to do |format|
   if @trade.save
    format.html { redirect_to @trade, notice: "Your request for trade has been submitted. You will be notified once it is approved or denied." }
    format.json { render :index, status: :created, location: @trade }
   else
    format.html { redirect_to @trade, notice: "Pick another amount" }
   end
  end
 end

 private
 def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item, :collateral_item, :shares)
 end
end

And then here's my Trade model

class Trade < ActiveRecord::Base
 belongs_to :trade_requester, class_name: "User"
 belongs_to :trade_recipient, class_name: "User"
 belongs_to :wanted_item, class_name: "Item"
 belongs_to :collateral_item, class_name: "Item"
end

Here's the form in my Item's show view:

<%= form_for(@trade) do |f| %>                  
 <%= f.hidden_field :wanted_item, value: @item.id %>
 <div class="field">
  <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
  <%= f.submit "Trade", class: "button minty-button wide-button" %>     
 </div>
<% end %>

The above code for the ItemsController posts to the TradesController create action, but I'm getting an error that says ActiveRecord::AssociationTypeMismatch in TradesController#createItem(#70095717466760) expected, got String(#70095657672800)

Why is that expecting an Item? It seems that if @trade creation results in error, then it should redirect to @trade.

Upvotes: 0

Views: 44

Answers (1)

Tom Aranda
Tom Aranda

Reputation: 6036

The quick solution is to change your hidden field from :wanted_item to :wanted_item_id:

  <%= form_for(@trade) do |f| %>                  
    <%= f.hidden_field :wanted_item_id, value: @item.id %>
    <div class="field">
      <%= f.text_field :shares, placeholder: "Pick a number between 1 and #{@item.shares}" %>
      <%= f.submit "Trade", class: "button minty-button wide-button" %>     
    </div>
  <% end %>

Also, make sure your trade_params method permits wanted_item_id:

def trade_params
  params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item_id, :collateral_item_id, :shares)
end

You may have a similar issue with :collateral_item in another form.

Upvotes: 1

Related Questions