我正在创建一个博客,当我想要展示一篇文章时,我遇到了问题
我已生成脚手架文章标题内容:文字,我只是生成一个名为欢迎的新控制器,其视图名为主页。我创建了新的控制器+视图,只是为了展示文章。对于这部分我没有发现问题,然后我创建了一个名为 post 的新控制器,其中一个名为 show 的视图仅用于显示所选文章的内容。的主页即可。
如何从另一个视图显示文章的内容?
我刚刚将@article = Article.find(params[:id])
添加到post_controller
然后当我点击主页中的文章标题时,我收到了这样的错误
无法找到带有'id'=
的文章
我错过了一些代码吗?
所以这是我的 welcome_controller
class WelcomeController < ApplicationController
def homepage
@articles = Article.all
end
end
欢迎/ homepage.html.erb
<div class="post-preview">
<% @articles.each do |article|%>
<h2 class="post-title"><%= link_to article.title, welcome_show_path %></h2>
<%= truncate article.content, length: 160 %>
<hr>
<% end %>
</div>
发表/ show.html.erb
<div class="post-heading">
<h1><%= @article.title %></h1>
</div>
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<p><%= @article.content %></p>
</div>
post_controller
class PostController < ApplicationController
def show
@article = Article.find(params[:id])
end
end
的routes.rb
Rails.application.routes.draw do
resources :articles
get 'welcome/homepage'
get 'post', to: 'post#show'
root 'welcome#homepage'
end
谢谢:)
答案 0 :(得分:1)
问题似乎在你的链接中:
<h2 class="post-title"><%= link_to article.title, welcome_show_path %></h2>
welcome_show_path
需要一个id。试试welcome_show_path(id: article.id)
。
<h2 class="post-title"><%= link_to article.title, welcome_show_path(id: article.id) %></h2>
如果不起作用,请尝试:post_show_path(id: article.id)
。
答案 1 :(得分:0)
你有3个控制器:
Article
=&gt;脚手架生成,它意味着预定义的路线。
Welcome
=&gt;只有一种方法,称为homepage
Post
=&gt;只有一种方法,称为show
。
路线:
resources :articles ##generate default routes
get 'welcome/homepage' ##generate only one route, URL would be -> homepage_welcome_path.
get 'post', to: 'post#show' ##it will call show method without any parameter.
root 'welcome#homepage'
第一: 得到'photos /:id',到:'照片#show'
在homepage.html.erb
<h2 class="post-title"><%= link_to article.title, welcome_show_path %></h2>
welcome_show_path ## expect show method in welcome controller, which is not exist.
第二:
要调用文章的show方法,您必须传递该文章的ID。
get 'articles/:id', to: 'articles#show' ##This route is already defined as you have `resource articles`. URL would be articles_path for the same.
在homepage.html.erb中替换
<h2 class="post-title"><%= link_to article.title, articles_path(id: article.id) %></h2>