简体   繁体   中英

Ruby on Rails: new params keep showing as “permitted: false”

I've been writing a new RoR app for practice. This is a basic app that is supposed to function as a lookup page for animals.

I've been working on the Create/New functions in the controller for my page. I would like to make it so that a user can enter in an animal, and have the animal save to the SQL database. Afterwards, the page should redirect to the newly created animal page.

Here's my animals_controller.rb:

class AnimalsController < ApplicationController
  def index
    @animals = Animal.all
  end

  def show
    @animal = Animal.find(params[:id])
  end

  def new
  end

  def create
    # render plain: params[:animal].inspect
    @animal = Animal.new(animal_params)

    @animal.save

     redirect_to @animal
  end

  private def animal_params
    params.require(:animal).permit(:name, :scientific_name, :range)
  end

end

Here is my views/animals/new.html.erb:

<h1> Add Animal </h1>

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

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

    <p>
    <%= f.label :range %> <br>
    <%= f.select :range, ['land', 'sea', 'sky', 'underground'], :prompt => 'Select One' %>
    </p>

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

When I try to enter in a new animal, here is what I get:

<ActionController::Parameters {"name"=>"cat", "scientific_name"=>"Felis catus", "range"=>"land"} permitted: false>

I'm wondering why I keep getting "permitted:false" when I have code in animals_controller.rb that states that these params are permitted! Can anyone point out anything or give me some suggestions?

Problem is with this line render plain: params[:animal].inspect because you are printing/accessing params directly without permission instead use :animal_params

render plain: animal_params.inspect

this lines @animal = Animal.new(animal_params) is fine. I guess your creating process works perfectly only.

Your params should look like

<ActionController::Parameters {"animal" => {"name"=>"cat", "scientific_name"=>"Felis catus", "range"=>"land"} } permitted: false>

Also, in the form, can you change :animal to @animal.

Alternatively, you can try this

params.require(:animal).permit(:name, :scientific_name, :range).permitted?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM