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
@[email protected]+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 @[email protected] 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
1 Answer 1
A lot of these logic could be moved to model. Rails provides lot of helpers for validation in your model.
class Item
validate :fund_vs_price, :fund_greater_than_zero
def fund_vs_price
errors.add(:fund, "Fund amount should not exceed price difference") if fund > price
end
def fund_greater_than_zero
errors.add(:fund, "No money specified.")
end
#overriding setter to do a sum every time it is assigned a value
def fund=(value)
write_attribute(:fund, fund.to_f + value)
end
end
With that, the controller becomes really simple.
def addFund
@item.fund = prams[:fund]
if @item.save
respond_to do |format|
format.html { redirect_to @item, success: 'Fund added' }
format.json {render :json =>{:status =>1,
:error=>"Done"}}
end
else
respond_to do |format|
format.html { redirect_to @item, error: @item.errors[:fund].join("\n") }
format.json {render :json =>{:status =>0,
:error=> @item.errors[:fund].join("\n")}}
end
end
end
If your model becomes too big to maintain, you can always use ActiveSupport concerns to separate it out into different modules. For eg, you could move everything related to validation into a separate module.
There might be some logical errors in the above code since its not tested. But it will give you an idea