Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

RoR: .create nils


(sorry for my english) If i want to upload a new record with :name and :date params, thats what i found:

Controller:

  class ActorController < ApplicationController
    def index
    end

    def new
      @actor = Actors.create
    end

    def create
      @actor = Actors.create(params[:actors])
      if @actor.save
        redirect_to actor_path, :notice => "Your actor was saved."
      else
        render "new"
      end
    end
  end

Model: (actors.rb)

  class Actors < ActiveRecord::Base 
    attr_accessible :birth, :name
  end

And the View: (new.html.erb)

<%= form_for(@actor) do |a| %>
  <%= a.text_field :name %>
  <%= a.text_field :birth %>
  <%= a.submit %>
<% end %>

And my output in local server console is:

Started PUT "/actor/40" for 127.0.0.1 at 2013-03-27 13:38:15 +0100
Processing by ActorController#update as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"BKhrP1Rfkco7r05wPT758M3CHQXRP5l5jcul77oTLPw=", "actors"=>{"name"=>"Bunny", "birth"=>"19/21/21"}, "commit"=>"Update Actors", "id"=>"40"}
   (1.2ms)  begin transaction
  SQL (0.7ms)  INSERT INTO "actors" ("birth", "created_at", "name", "updated_at") VALUES (?, ?, ?, ?)  [["birth", nil], ["created_at", Wed, 27 Mar 2013 12:38:15 UTC +00:00], ["name", nil], ["updated_at", Wed, 27 Mar 2013 12:38:15 UTC +00:00]]
   (197.8ms)  commit transaction
   (0.2ms)  begin transaction
   (0.1ms)  commit transaction
Redirected to http://localhost:3000/actor/40
Completed 302 Found in 209ms (ActiveRecord: 200.0ms)

Solution

  • Please edit the following:

    1) Edit your Model:

    class Actor < ActiveRecord::Base  # Class name should be Singular
      attr_accessible :birth, :name
    end
    

    2) Edit your Controller:

      class ActorsController < ApplicationController # Note Here the controller name should be plural without space
        def index
        end
    
        def new
          @actor = Actor.new  # In the new action, it should be classname.new not create
        end
    
        def create
          @actor = Actor.create(params[:actor]) # Here also the Actor class name should be singular
          if @actor.save
            redirect_to actor_path, :notice => "Your actor was saved."
          else
            render "new"
          end
        end
      end
    

    PS:

    1) In the View folder name should be Plural too, so your folder name is app/view/actors. 2) Change your controller name like actors_controller. 3) In your routes, it should be resources :actors. 4) You need to allign your code with correct indetation to find where you starting and where you ending. It's the good way to start coding. It will resolve your 50% problem to find where you doing wrong.