Home > Net >  When I tried to get input from the Form on ruby on rails, I am getting back hash array instant of si
When I tried to get input from the Form on ruby on rails, I am getting back hash array instant of si

Time:11-07

Here is my HTML code

<h1>Create new Cat</h1>
<form action="/cats" method= "POST">
    <input type="text" name="cat[name]">

    <input type="submit" value="Create Cat!">
</form>

When I try to get the input with the above code by typing Loki in the box as cat name, I got Parameters: {"cat"=>{"name"=>"Loki"}}, the saved name become {"name"=>"Loki"} and the Json format is {"id":19,"name":"{"name"=\u003e"Loki"}","created_at":"2021-11-07T07:03:50.140Z","updated_at":"2021-11-07T07:03:50.140Z"}.

What I am expecting to get is just "Loki".

This is my create method from cats_controller.rb

    def create
        #POST /cats
        @cat = Cat.new(name: params[:cat].permit(:name))
        if @cat.save
            redirect_to cat_url(@cat)
        else
            render :new
            #render json: @cat.errors.full_messages, status: :unprocessable_entity
        end
    end

CodePudding user response:

You are much better of using strong parameters as is the Rails standard of doing things. params[:cat].permit(:name) just permits the params, doesn't read from it, you would have to do params[:cat].permit(:name)[:name] to get to the name itself.

As said however, this is the Rails way of doing this, much cleaner code.

def create
  @cat = Cat.new(safe_params)
  # ...
end

def safe_params
  params[:cat].permit(:name)
end

  • Related