Tri Nguyen
Tri Nguyen

Reputation: 1808

Form fields are not saved into database - ruby on rails

I have a form here https://pastebin.com/JfXr054y

In routes.rb I have

resources :landslides, only: [:new, :create, :index]

In landslides_controller.rb I have

  def new
    @landslide = Landslide.new(landslide_params)

    @landslide.save
    render plain: @landslide.inspect
  end

and

def landslide_params
  params.require(:landslide).permit(:total_id, :year_id, :start_date, :end_date, :day_number, :continent, :country, :location, :type, :admin_level, :new_lat, :new_long, :mapped, :spatial_area, :fatalities, :injuries, :notes, :sources)
end

Why the form isn't saved into the table?

Upvotes: 0

Views: 931

Answers (1)

SteveTurczyn
SteveTurczyn

Reputation: 36860

new is the wrong method in which to perform #save. that should be done in create

  def new
    @landslide = Landslide.new
  end

  def create
    @landslide = Landslide.new(landslide_params)
    if @landslide.save
      render plain: @landslide.inspect
    else
      render :new
    end
  end

Also, your form looks wrong. The location of the form data in your returned params depends on the control's name field, not on the id

Instead of

%input#location.form-control{:type => "Location"}

I'd expect to see

%input#landslide_location.form-control{:type => "text", :name => "landslide[location]"}

Upvotes: 1

Related Questions