bevinh
bevinh

Reputation: 11

Rails 5 not saving data

After bashing away at this for two days, I'm completely stumped. I can't seem to save any data for any models that include this (outlined below) or anything I added afterward.

I have a migration that looks like this:

class CreateScenarios < ActiveRecord::Migration[5.1]
 def change
  create_table :scenarios do |t|
  t.string :title
  t.text :description
  t.string :scenariotype
  t.references :activity, foreign_key: true
  t.timestamps
   end
 end
end

My schema:

create_table "scenarios", force: :cascade do |t|
t.string "title"
t.text "description"
t.string "scenariotype"
t.bigint "activity_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["activity_id"], name: "index_scenarios_on_activity_id"
end

Model looks like this:

class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activities
end

In my controller, I have these params set:

def scenario_params
  params.require(:scenario).permit(:title, :description, :scenariotype, :activity_id)
end

The new method looks like this:

def new
   @scenario = Scenario.new
   @activity = Activity.find(params[:activity])
end

And the create method looks like this:

def create
   @scenario = Scenario.new(scenario_params)
   @activity = Activity.find(@scenario.activity_id)
   @scenario.save
   redirect_to new_page_path(scenario: @scenario.id)
end

When I try to save a record, even in the console, from this migration or any later migrations, it won't save and rolls back because it isn't autoincrementing. So running something like this:

scenario=Scenario.new(:activity_id =>1, :title =>"asfdasdf", :scenariotype=>"Teaching", :description=>"asdfadsf")

results in something like this

<Scenario id: nil, title: "asfdasdf", description: "asdfadsf", scenariotype: "Teaching", activity_id: 1, created_at: nil, updated_at: nil>

And then it rolls back because it's missing an id.

I've dropped and recreated the databases. I thought something might be wrong with a previous migration, but those both work just fine. I'm hoping I'm missing something incredibly straightforward and stupid, but I'm just not seeing it. Database is Postgres.

Thanks in advance for any help anyone can provide.

Upvotes: 1

Views: 614

Answers (1)

wbucko
wbucko

Reputation: 95

You have mistake in your Scenario model - when setting belongs_to association, singular form should be used. So instead of belongs_to :activities your model should look like:

class Scenario < ApplicationRecord
  has_many :pages
  belongs_to :activity
end

Upvotes: 1

Related Questions