psgs
psgs

Reputation: 93

Rails unintentionally inserts default values into database

I have created two controller actions in rails. One that attempts to represent information from a database visually, and one that creates that information if it is not found in the database.

def show
  if Stock.not_exists?(params[:symbol])
    create
  end
$stock = Stock.find(params[:symbol])
@input = Stock.getoverview(params)
if @input === 404
  not_found
else
  @data = # Data is pulled from API
  respond_to do |format|
    format.html # show.html.erb
    format.json { render json: @stock }
  end
end
end

def create
  stock = Stock.new
  stock.symbol = params[:symbol]
  stock.name = # Data is pulled from API
  stock_saved = stock.save
  if stock_saved
    render json: stock, status: :created
  else
    render json: stock.errors, status: :unprocessable_entity
  end
end

When the "show" controller action is triggered by an HTML request, the controller attempts to create an database entry that contains the data. Unfortunately, the controller issues the following SQL query when attempting to save the created "Stock" model:

  SQL (2.0ms)  INSERT INTO "stocks" DEFAULT VALUES

When the database is analysed, all columns appear to be essentially null, when they should contain data processed in the "create" controller action.

Is there any way I can fix this?

My database schema and "Stock" model can be found at: https://gist.github.com/psgs/e79e9efac05c235678ed

Upvotes: 0

Views: 212

Answers (1)

Uri Agassi
Uri Agassi

Reputation: 37409

You should not call create as a method. Extract the relevant part of the create to an external method, and use that one:

def show
  if Stock.not_exists?(params[:symbol])
    do_create(params[:symbol])
  end
  $stock = Stock.find(params[:symbol])
  @input = Stock.getoverview(params)
  if @input === 404
    not_found
  else
    @data = # Data is pulled from API
    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @stock }
    end
  end
end

def do_create(symbol)
  stock = Stock.new
  stock.symbol = symbol
  stock.name = # Data is pulled from API
  stock.save
end

def create
  stock_saved = do_create(params[:symbol])
  if stock_saved
    render json: stock, status: :created
  else
    render json: stock.errors, status: :unprocessable_entity
  end
end

Upvotes: 1

Related Questions