0

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

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but same problem still.
change the type field name with different name, like plan_type or something else and then try, as type is used by rails for STI api.rubyonrails.org/classes/ActiveRecord/Base.html
ah, I see - it's a reserved name. do I need to change the column name in the DB or just in the form?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.