0

I have the following model in my Rails 3.2.13 build. I am trying to use it to insert data into my database.

  class Financials < ActiveRecord::Base
    #attr_accessible :description, :stock
    attr_accessible :symbol, :cur_price
    sym = Financials.new(:symbol => test, :cur_price => 10)
    sym.save

  end

but when I try to run the code I get the following error:

financials.rb:1:in `': uninitialized constant ActiveRecord (NameError)

I checked through SO and found others that had similar errors and they suggested that I add entries in the environment.rb ruby on rails pluralization help?

I added the following to the environment.rb file:

  Inflector.inflections do |inflect|
      inflect.irregular 'financialss', 'financials'
  end

but it did resolve my issue. Thanks in advance

Community
  • 1
  • 1
rahrahruby
  • 673
  • 4
  • 11
  • 28

1 Answers1

2

You don't create new objects inside the definition of the model. You should be doing this in the create action of the controller.

Given your model:

class Financial < ActiveRecord::Base
  attr_accessible :symbol, :cur_price

  # validations, methods, scope, etc.
end

You create the new Financial object in your controller and redirect to the appropriate path:

class FinancialsController < ApplicationController
  def create
    @financial = Financial.new(params[:financial])
    if @financial.save
      redirect_to @financial
    else
      render :new
    end
  end

  def new
    @financial = Financial.new
  end

  def show
    @financial = Financial.find(params[:id])
  end
end
James
  • 4,599
  • 2
  • 19
  • 27
  • Excellent I added your recommendations to my controller, so where would I add the sym = Financials.new(:symbol => test, :cur_price => 10) sym.save statements? – rahrahruby May 20 '13 at 17:48
  • You don't. That's what `@financial = Financial.new(params[:financial])` replaced. You can accept input from a form in the view. http://guides.rubyonrails.org/form_helpers.html – James May 20 '13 at 18:04