Reputation: 119
In my view file I have
%td= link_to 'Destroy', fund_subfund_path(@fund, subfund), :method => :delete, :data => { :confirm => 'Are you sure?' }
My controller has
def destroy @subfund = Subfund.find(params[:id]) fund_id = @subfund.fund_id nickname = @subfund.nickname if @loans.empty? @subfund.destroy respond_to do |format| format.html { redirect_to fund_path(fund_id), notice: 'Subfund ' + nickname + ' was destroyed.' } format.json { head :no_content } end else respond_to do |format| format.html { redirect_to fund_path(fund_id), notice: 'Subfund ' + nickname + " has Loans, so can't be destroyed." } format.json { head :no_content } end end end
The redirects and messages work fine. My problem is that even if @loans is not empty and the @subfund.destroy action is not carried out, the "Are you sure?" confirmation still appears.
How do I intercept this method before the confirmation message?
I did try link_to_if as an alternative, but that still displays "Destroy" as an inactive link, which I think would be confusing to the user.
Upvotes: 1
Views: 224
Reputation: 167
Baylor Rae's is a good answer, in particular it checks in realtime if there are any loans.
You might also consider a simpler alternative: when you render the page where the delete link_to is, you might put or not the delete button based on wether there are or not loans.
I do not speak HAML either, but I'm pretty sure is strightforward to include your %td= link_to in an if ... else ... end
statement.
If the button should not be rendered you can write a text that explains why the user cannot delete that object. This way it's easy for the user to understand the situation, rather than having to click on the delete link to find out you cannot perform that action.
Cheers,
Upvotes: 2