如何从另一个视图显示文章的内容

how to show article's content from another view

我正在创建一个博客,但当我想显示一篇文章时遇到了问题

我已经生成了脚手架文章标题 content:text,我刚刚生成了一个名为 welcome 的新控制器,其视图名为 homepage .我创建了新的控制器+视图只是为了显示文章。对于这部分我没有发现问题,然后我创建了一个名为 post 的新控制器,其视图名为 show 仅用于显示 主页 中所选文章的内容。

如何从另一个角度显示文章内容? 我刚刚将 @article = Article.find(params[:id]) 添加到 post_controller 然后当我点击主页中的一篇文章标题时,我得到了这样的错误

Couldn't find Article with 'id'=

我是不是遗漏了一些代码?

所以这是我的 welcome_controller

class WelcomeController < ApplicationController
  def homepage
    @articles = Article.all
  end
end

welcome/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>

post/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

谢谢:)

问题似乎出在您的 link:
<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)

您有 3 个控制器:

Article => 由脚手架生成,即预定义路由。 Welcome => 只有一种方法,叫做 homepage Post => 只有一种方法,叫做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',到:'photos#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.

第二个:

要调用文章的显示方法,您必须传递该文章的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>