user2656127
user2656127

Reputation: 665

Cannot enter simply form information into SQLite DB (Rails)

So, I'm running into a fairly simple problem, where I cannot enter some simple form values into my SQLite DB (Rails).

Interestingly, the code doesn't fail - I submit the form, and am redirected successfully to the correct URL - and a record IS inserted into the DB, but the columns "name, type and user_id" are not filled with anything. To clarify, the columns are blank, for that new record.

If I comment out the code in the "create" and simply spit out the params (render plain: params[:plan].inspect) I do see all the correct parameters filled out, so I have a feeling there must be something wrong in the line:

@plan = Plan.new(params[:plan])

I'm really stuck here, any guidance would be much appreciated!

The create form

<h1> Create a new plan </h1>

<%= form_for :plan, url: plans_path do |f| %>
  <p>
    <%= f.label :name %><br>
    <%= f.text_field :name %>
  </p>

  <p>
    <%= f.label :type %><br>
    <%= f.text_field :type %>
  </p>

  <%= f.hidden_field :user_id, :value => current_user.id %>

  <p>
    <%= f.submit %>
  </p>
<% end %>

plans_controller.rb

class PlansController < ApplicationController

  def index
    @plans = Plan.all
  end

  def show
    @plan = Plan.find(params[:id])
  end

  def new
    @plan = Plan.new
  end

  def create
    #render plain: params[:plan].inspect
    params.permit!
    @plan = Plan.new(params[:plan])
    if @plan.save
      redirect_to @plan
    else
      redirect_to dashboard_path, :notice => "Plan NOT Created!"
    end
  end

end

The Model

class Plan < ActiveRecord::Base

end

Upvotes: 0

Views: 24

Answers (1)

Shamsul Haque
Shamsul Haque

Reputation: 2451

Edit the plans_controller.rb:-

def create
  #render plain: params[:plan].inspect
  @plan = Plan.new(plan_params)
  if @plan.save
    redirect_to @plan
  else
    redirect_to dashboard_path, :notice => "Plan NOT Created!"
  end
end

private

def plan_params
  params.require(:plan).permit(:name,:type,:user_id)
end

Change the field name type as :-

rails g migration rename_fields_in_plans

class RenameFieldsInPlans < ActiveRecord::Migration
  def change
    rename_column :plans, :type, :plan_type
  end
end

Then run the command:-

rake db:migrate

Upvotes: 1

Related Questions