Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
349 views
in Technique[技术] by (71.8m points)

Rails 5.2.3 missing required keys: [:id] in new.html.erb form

I am new to Ruby on Rails.

I have this controller:

class MynewsController < ApplicationController
    skip_before_action :authenticate_user!

    def new
    end

    def show
    end

    def create
        render plain: params[:mynew].inspect
    end
end

this row in routes.rb:

 resources :mynews

and this new.html.erb file:

<h1>New Mynews</h1>

<%= form_with scope: :mynew, local: true do |form| %>
    <p>
      <%= form.label :title %><br>
      <%= form.text_field :title %>
    </p>
   
    <p>
      <%= form.label :body %><br>
      <%= form.text_area :body %>
    </p>
   
    <p>
      <%= form.submit %>
    </p>
  <% end %>

It display the form and when i hit submit it displays the expected No route matches [POST] "/mynews/new" error

The problem is when i add the url parameter in the form_with row:

<%= form_with scope: :mynew, url: mynews_path, local: true do |form| %>

http://localhost:3000/mynews/new doesn't display the form and gives

No route matches {:action=>"show", :controller=>"mynews"}, missing required keys: [:id]

error.

I can't find what is the problem. Can you help me, please?

question from:https://stackoverflow.com/questions/66060464/rails-5-2-3-missing-required-keys-id-in-new-html-erb-form

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Rather than using form_with scope: try this instead.

In your controller's new action you need to create a new unsaved record. I have no idea what your model is called, so I'm guessing based on your controller name:

def new
  @mynew = Mynew.new
end

Next, in your view, do the form like this:

<%= form_with model: @mynew, local: true do |form| %>

And it'll handle the paths etc for you.

However, I suspect your model probably isn't called Mynew, in which case you'd have to specify the url.

Assuming your model is actually called something like Article, I'd advise you to also name your controller ArticlesController. If you want the actual URL to be different you can configure that in your routes file ... but creating/updating/deleting an Article should be handled by the ArticlesController, regardless of what URL the users see.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...