So I have this code that i use for addition of funds to a certain item.
def addFund
fund=params[:fund]
if(fund.to_i>0)
@fund=fund
if(@item.fund+fund.to_f>@item.price) #the fund added should be less than price-current fudn
respond_to do |format|
format.html { redirect_to @item, error: 'Fund amount should not exceed price difference' }
format.json {render :json =>{:status =>0,
:error=>"Fund amount cannot be greater than price difference "}}
end
else
#Finally do the addition
@item.fund=@item.fund+fund.to_f
@item.save
respond_to do |format|
format.html { redirect_to @item, success: 'Fund added' }
format.json {render :json =>{:status =>1,
:error=>"Done"}}
end
end
else
respond_to do |format|
format.html { redirect_to @item, error: 'No money specified.' }
format.json {render :json =>{:status =>0,
:error=>"Money not specified"}}
end
end
end
So this is how it works:
First we check if the fund(POST ParameteR) is non zero fund.to_i>0
and respond accordingly giving an error message if it isn't
@item.fund = the current funding the item has
@item.price = the price of item
fund = the fund to be added(POST)
fund must be less than @item.price-@item.fund since there is no point in accepting funds greater than the price, the item can already be bought
Then finally if all this works, then we add the funds to the item and show him a message.
So that's pretty much it. I am thinking there has to be a way of clubbing the responses and replying at one time. I have no idea how respond_to actually works. Ruby has blocks that you won't find in java or C++ or PHP