Reputation: 69
When I try to customize my bid_params to add a parameter to the database, my strong parameters are not working for some reason. I need to be able to have the current_user passed into the database on the creation of a bid. This object is nested in a has_many belongs_to relationship with Auctions. Here is my controller:
class BidsController < ApplicationController
def index
@auction = Auction.find(params[:auction_id])
@bids = @auction.bids
end
def new
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.build
end
def create
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.create(bid_params)
if @bid.save
flash[:success] = "Bid has been successfully placed."
redirect_to @auction
else
flash[:error] = @bid.errors.full_messages.join('. ')
render 'new'
end
end
def destroy
@auction = Auction.find(params[:auction_id])
@bid = @auction.bids.find
@bid.destroy
flash[:notice] = "Successfully destroyed Bid."
redirect_to auction_url(@bid.article_id)
end
private
def bid_params
params.require(:bid).permit(:auction_id).merge(bidder: current_user)
end
end
and Stack Trace:
Started POST "/auctions/2/bids" for 127.0.0.1 at 2014-12-06 08:54:35 -0600
Processing by BidsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6x4hV8y323a10kaJN5Rubj1z3uhUrSDQrD6aoaWCUhk=", "commit"=>"Create Bid", "auction_id"=>"2"}
Auction Load (0.1ms) SELECT "auctions".* FROM "auctions" WHERE "auctions"."id" = ? LIMIT 1 [["id", 2]]
Completed 400 Bad Request in 2ms
ActionController::ParameterMissing (param is missing or the value is empty: bid)
New Form:
<h1>Create a New Bid</h1>
<%= form_for ([@auction, @bid]) do |f|%>
<p>
<%= f.submit %>
</p>
<%end%>
Thanks!
Upvotes: 2
Views: 1158
Reputation: 2558
Look at parameters that controller received:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"6x4hV8y323a10kaJN5Rubj1z3uhUrSDQrD6aoaWCUhk=", "commit"=>"Create Bid", "auction_id"=>"2"}
And then you try to permit these params:
def bid_params
params.require(:bid).permit(:auction_id).merge(bidder: current_user)
end
And error was thrown in this operation: params.require(:bid)
as this method suppose your params looks like:
{ ..., "bid" => { "auction_id" => "2" } }
Hence you may change your view/js that sends params or change def bid_params
implementation to:
def bid_params
params.permit(:auction_id).merge(bidder: current_user)
end
Upvotes: 1