英文:
undefined method `articles_path' for #<ActionView::Base:0x0000000000b450>
问题
以下是翻译好的内容:
这是名为Articles的控制器
def new
@article = Article.new
end
def show
@article = Article.find(params[:id])
end
def create
@article = Article.new(article_params)
if @article.save
redirect_to @article
else
render :new, status: :unprocessable_entity
end
end
这是视图
<h1>New Article</h1>
<%= form_for(@article) do |form| %>
<div>
<%= form.label :title %><br>
<%= form.text_field :title %>
</div>
<div>
<%= form.label :body %><br>
<%= form.text_field :body %>
</div>
<div>
<%= form.submit %>
</div>
<% end %>
这是路由
get 'articles/new', to: 'articles#new'
post 'articles/create', to: 'articles#create'
当我尝试访问路由 <http://localhost:3000/articles/new>
时,出现错误:undefined method `articles_path' for #ActionView::Base:0x0000000000b450
英文:
This is the controller named Articles
def new
@article =Article.new
end
def show
@article=Article.find(params[:id])
end
def create
@article=Article.new(article_params)
if @article.save
redirect_to @article
else
render :new, status: :unprocessable_entity
end
end
This is the view
<h1>New Article</h1>
<%form_for(@article) do |form|%>
<div>
<%=form.label :title%><br>
<%=form.text_field :title%>
</div>
<div>
<%=form.label :body%><br>
<%=form.text_field :body%>
</div>
<div>
<%=form.submit%>
</div>
<%end%>
This is the routes
get 'articles/new', to: 'articles#new'
post 'articles/create', to: 'articles#create'
when I want to access the route <http://localhost:3000/articles/new> it gives error undefined method `articles_path' for #<ActionView::Base:0x0000000000b450>
答案1
得分: 1
错误发生在form_for
中。当提供新的article
对象时,它必须猜测表单将提交到的路径。按照惯例,它尝试执行"#{object.model_name.plural}_path"
您的路由没有名称,也不生成辅助方法。您可以使用以下方式显式地为它们命名:
get 'articles/new', to: 'articles#new', as: :new_article
post 'articles/create', to: 'articles#create', as: :articles
或者使用resources
快捷方式:
resources :articles, only: %i[new create]
英文:
The error is raised within form_for
. When new article
object is given, it has to guess the path the form will be submitted to. Following convention, it tries to execute "#{object.model_name.plural}_path"
Your routes has no names and do not generate helpers. You can give them names explicitly with:
get 'articles/new', to: 'articles#new', as: :new_article
post 'articles/create', to: 'articles#create', as: :articles
Or use resources
shortcut instead:
resources :articles, only: %i[new create]
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论