Alex Teut
Alex Teut

Reputation: 844

Created objects do not save in database

What did I do:

  1. create a new ruby app rails new campaigns_manager
  2. move to campaigns_manager directory, generate first scaffold campaigns rails generate scaffold campaign name:string and migrate
  3. add root route root to: 'campaigns#index', as: 'campaigns'

Such a few strings of code. Then I start server to test it. Everything looks and works ok, but when I try to add a new campaign, nothing saves. After pressing "Create campaign" button I receive in console something like that:

Started POST "/" for 127.0.0.1 at 2012-04-25 22:30:40 +0300
Processing by CampaignsController#index as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"sKom3YBDEbOcqbSt3gLGWPqBNeqkEw6M59hlwrmH4tM=", "campaign"=>{"name"=>"test"}, "commit"=>"Create Campaign"}
  Campaign Load (0.3ms)  SELECT "campaigns".* FROM "campaigns" 
  Rendered campaigns/index.html.erb within layouts/application (0.9ms)
Completed 200 OK in 37ms (Views: 35.4ms | ActiveRecord: 0.3ms)

then I redirect to campaigns list and there is no new campaign. Table campaigns in db\development.sqlite3 is empty.
Furthermore, I add print methods to campaigns controller to check if I call correct methods. And I see, that create method is not called when I press "Create campaign" button.
My campaigns/new view:

<h1>New campaign</h1>

<%= form_for(@campaign) do |f| %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

<%= link_to 'Back', campaigns_path %>

Why cannot I save my campaigns to database?

Upvotes: 0

Views: 73

Answers (2)

Ben
Ben

Reputation: 13615

The problem is in the routes.rb file.

root to: 'campaigns#index', as: 'campaigns'

The alias as: 'campaigns' tries to consume all requests. There is no need to add an alias to your root directive, it already has one by default: as: 'root'

Your routes.rb file has to look something like this:

resources :campaigns
root to: 'campaigns#index'

More on Routes in Rails Guides

Upvotes: 1

tsherif
tsherif

Reputation: 11710

It would help to see the view code in campaigns/new, but clearly the form there is posting to /, which you can see from the log, is being handled by the index action (which is as it should be according to your routes). You have to make sure your form in campaigns/new is posting to /campaigns (which in Rails RESTful routing resolves to the create action). If you're using form_for (which I think is what the scaffold generates), it should look something like this:

<%= form_for @campaign do |f| %> 

Upvotes: 0

Related Questions