gpt4 book ai didi

ruby-on-rails - #<#:0x007fe3546d58f0> 的未定义方法 `posts_path'

转载 作者:数据小太阳 更新时间:2023-10-29 08:30:26 24 4
gpt4 key购买 nike

我是 Rails 的新手,我遇到了这个错误:

undefined method `posts_path' for #<#<Class:0x007fe3547d97d8>:0x007fe3546d58f0>

我已经在下面发布了我的文件,请记住我是 Rails 的新手,所以非常感谢简单的解释!

路线.rb:

Rails.application.routes.draw do
get '/post' => 'post#index'
get '/post/new' => 'post#new'
post 'post' => 'post#create'
end

post_controller.rb:

class PostController < ApplicationController
def index
@post = Post.all
end

def new
@post = Post.new
end

def create
@post = Post.new(post_params)
if @post.save
redirect_to '/post'
else
render 'new'
end
end

private
def post_params
params.require(:post).permit(:content).permit(:title)
end
end

新的.html.erb:

<%= form_for(@post) do |f| %>
<div class="field">
<%= f.label :post %><br>
<%= f.text_area :title %>
<%= f.text_area :content %>
</div>
<div class="actions">
<%= f.submit "Create" %>
</div>
<% end %>

最佳答案

我猜 form_for(@post) 期望有一个名为 posts_path 的方法,但一个不存在,因为它没有在你的路由中定义文件。尝试替换:

Rails.application.routes.draw do
get '/post' => 'post#index'
get '/post/new' => 'post#new'
post 'post' => 'post#create'
end

Rails.application.routes.draw do
resources :posts, only: [:new, :create, :index]
end

编辑:更多信息:

http://guides.rubyonrails.org/form_helpers.html 阅读有关表单助手的完整页面,特别是阅读“2.2 将表单绑定(bind)到对象”部分以及以下内容:

When dealing with RESTful resources, calls to form_for can get significantly easier if you rely on record identification. In short, you can just pass the model instance and have Rails figure out model name and the rest:

## Creating a new article
# long-style:
form_for(@article, url: articles_path)
# same thing, short-style (record identification gets used):
form_for(@article)

## Editing an existing article
# long-style:
form_for(@article, url: article_path(@article), html: {method: "patch"})
# short-style:
form_for(@article)

Notice how the short-style form_for invocation is conveniently the same, regardless of the record being new or existing. Record identification is smart enough to figure out if the record is new by asking record.new_record?. It also selects the correct path to submit to and the name based on the class of the object.

因此,无论是否有意,当您说 form_for(@post) 时,您是在要求 Rails 根据您的 的名称猜测您的表单应该提交到的路径>@post 变量。您定义的路线与 rails 预期的路线不匹配。

有关 Rails 中路由的更多信息,请阅读 http://guides.rubyonrails.org/routing.html 上的整个页面,并特别注意“2 资源路由:Rails 默认值”部分。您的 form_for(@post) 将假设您正在使用“资源路由”,这是我切换到的。

至于为什么你得到一个新的错误?在您的应用程序中的其他地方,您希望使用以前的自定义路由,而现在您使用的是 Rails“资源路由”,因此您的路径名称会有所不同。 No route matches [GET] "/post/new"因为现在路由匹配 No route matches [GET] "/posts/new"(注意复数 posts)。

关于ruby-on-rails - #<#<Class :0x007fe3547d97d8>:0x007fe3546d58f0> 的未定义方法 `posts_path',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39905556/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com