问题描述:

  • Ruby 2.2.4
  • Rails 4.2.6
  • PostgreSQL 9.5

I am trying to save a simple model, but when I submit the form, my browser url shows this "http://localhost:8080/notes/new?utf8=%E2%9C%93&authenticity_token=z0cyVNfUKYWDSDASDWFFZ96zj29UTtDYe8dLlKrI6Mbznb2SrTWNm%2BQ91D2s2AASD2345Fl3fTOneCC2dNg%3D%3D&note%5Btitulo%5D=ddddddd&note%5Bconteudo%5D=dddddddddddddddddd&commit=Create"

I am curious about this because other project, it has the same methods, same routes, the only difference is the model that only have one column, but it works fine.

def change

create_table :notes do |t|

t.text :titulo

t.text :conteudo

t.timestamps null: false

end

My controller: notes_controller.rb

 def new

@note = Note.new

end

def create

@note = Note.new(note_params)

if @note.save

redirect_to '/'

else

render 'new'

end

end

private

def note_params

params.require(:note).permit(:titulo,:conteudo)

end

my form

<%= form_for(@note) do |f| %>

<div class="field">

<%= f.label :titulo %><br>

<%= f.text_area :titulo %>

<%= f.label :conteudo %><br>

<%= f.text_area :conteudo %>

</div>

<div class="actions">

<%= f.submit "Create" %>

</div>

<% end %>

my routes

Rails.application.routes.draw do

root 'notes#index'

get 'notes/new' => 'notes#new'

post 'notes' => 'notes#create'

I saw this post Rails form issuing GET request instead of POST request

but does not work for me.

Edit:

I fix it thanks to Anthony E, his answer made me look back to code and realize that I have a form inside a form. The outer form was in application.html.erb.

Thanks to all.

网友答案:

Rails can't infer the appropriate form route from your model. Try explicitly setting the form URL and submit method in your form_for:

form_for @note, url: "/notes", as: :note, html: { method: :post } do |f|
end

Alternatively, it may be simpler to use resourceful routing:

In routes.rb:

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

This will create the following routes:

GET /notes/new  # Maps to NotesController#new
POST /notes     # Maps to NotesController#create
GET /notes      # Maps to NotesController#index
相关阅读:
Top