How to not let the user continue with the ‘action’ if something is set to ‘true’

I'm creating a _sell_ action that, when the user clicks on the SELL button it is triggered. The user must have available stocks ( != 0 ) of that specific company, so if the user have 0 stocks of this company, the button won't do anything. It should be like a form that do not let the user Sing Up unless he completes everything ( a red bar appears saying what he have to do ).
Here is the sell action code, on my controller.

def sell
team_id = 9
find_the_specific_row = current_user.user_stocks.find_by team: team_id

if find_the_specific_row.nil? or find_the_specific_row == 0

find_the_specific_row.update(:amount => find_the_specific_row.amount - 1)
redirect_to portfolios_path

Note that the space that is blank ( the if statement) is where I should write what i am trying to do

2 thoughts on “How to not let the user continue with the ‘action’ if something is set to ‘true’”

  1. You can opt to do *nothing*, and allow the action to complete. The controller will attempt to render the “sell” template by default.

    Consider though that you do have business logic that prevents the action from completely. At a minimum you should indicate to the user that the action failed, and why.

    You could set a flash message to do this.

  2. This is best handled by a validator in your model.

    class UserStock < ApplicationRecord # numericality check if value is a number (in this case, not nil) # greater_than will confirm the starting value is greater than 0 validates :amount, numericality: { greater_than: 0 } end # I'm assuming that this is where your sell method is class UserStocksController < ApplicationController def sell team_id = 9 @user_stock = current_user.user_stocks.find_by team: team_id # if the stock is valid, it'll update. This accomplishes both tasks at once if @user_stock.update(amount: @user_stock.amount - 1) redirect_to portfolios_path else # assuming that this is on an edit page respond_to do |format| format.html { render :edit } format.json { render json: @user_stock.errors } end end end end # Then in your view, if you're using a form: <%= form_for @user_stock do |f| %>
    <% if @user_stock.errors.any? %>

      <% @user_stock.errors.full_messages.each do |msg| %>

    • <%= msg %>
    • <% end %>

    <% end %>

    <% end %>

    # the errors returned by the validator would be:
    # numericality: “amount is not a number”
    # greater_than: “amount must be greater than 0”

    Hope that helps!


Leave a Comment