我有两个控制器 - ItemsController
和TradesController
。我正在@trade
ItemsController
操作中构建#show
,该操作会使用表单发送到TradesController
#create
操作。
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
然后这是我的Trade
模型
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
以下是Item's
show
视图中的表单:
<%= 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 %>
ItemsController
TradesController
帖子的create
帖子的上述代码,但我收到的错误是ActiveRecord::AssociationTypeMismatch in TradesController#createItem(#70095717466760) expected, got String(#70095657672800)
为什么期待Item
?似乎如果@trade
创建导致错误,那么它应该重定向到@trade
。
答案 0 :(得分:1)
快速解决方案是将隐藏字段从:wanted_item
更改为: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 %>
另外,请确保trade_params
方法允许wanted_item_id
:
def trade_params
params.require(:trade).permit(:trade_requester, :trade_recipient, :wanted_item_id, :collateral_item_id, :shares)
end
您可能在另一种形式下遇到与:collateral_item
类似的问题。