首页 > 解决方案 > 如何使用 Rails 5 创建动态侧边栏而不是索引页面?

问题描述

我是 Rails 5 的初学者,我正在开发一个 NoteTaking 应用程序。

考虑到笔记应用程序的结构,我希望有一个动态侧边栏,所有创建的帖子都显示在侧边栏上(以及可能在侧边栏中滚动的能力),而不是有一个索引页面。

这就是我希望它的样子(查看下图)。虽然我确实看到侧边栏上出现了帖子,但它们突然出现多次,如图所示。

在此处输入图像描述

以下是相关代码:

application.html.erb

<body>
<div id="sidebar">
  <div id="logo">
    <%= link_to root_path do %>
      <%= image_tag "logo.svg" %>
    <% end %>
  </div>

  <ul>
    <li class="category">Notes</li>
    <% @posts.all.each do |post| %>
      <li><%= post.title %></li>
    <% end %>
  </ul>

  <ul>
    <li class="category">Social</li>
    <li><%= link_to "Twitter", "#" %></li>
    <li><%= link_to "Facebook", "#" %></li>
    <li><%= link_to "Email", "#" %></li>
  </ul>
  <p class="sign_in">Admin Login</p>
</div>

<div id="main_content">
  <div id="header">
    <p>All Posts</p>
    <div class="buttons">
      <button class="button"><%= link_to "New Post", new_post_path %></button>
      <button class="button">Log Out</button>
    </div>
  </div>
  <% flash.each do |name, msg| %>
    <%= content_tag(:div, msg, class: "alert") %>
  <% end %>
  <%= yield %>
</div>

有一个持续性错误说:.nil:NilClass 中的未定义方法“全部” application.html.erb。更具体地说,这里:

 <ul>
   <li class="category">Notes</li>
   <% @posts.all.each do |post| %>
     <li><%= post.title %></li>
   <% end %>
 </ul>

这是我尝试过的(不知道这是否是这样做的方法..),我@posts通过将其添加到application_controller.rb.

class ApplicationController < ActionController::Base
  def index
    @posts = Post.all.order("created_at DESC")
  end  
end

我还包括@posts在 new 和 create 方法中,posts_controller.rb如下所示:

def new
    @posts = Post.all.order("created_at DESC")
    @post = Post.new
  end

  # GET /posts/1/edit
  def edit
  end

  # POST /posts
  # POST /posts.json
  def create
    @posts = Post.all.order("created_at DESC")
    @post = Post.new(post_params)

    respond_to do |format|
      if @post.save
        format.html { redirect_to @post, notice: 'Post was successfully created.' }
        format.json { render :show, status: :created, location: @post }
      else
        format.html { render :new }
        format.json { render json: @post.errors, status: :unprocessable_entity }
      end
    end
  end

我不知道现在如何进行。你能帮我么?!我没有人的土地......谢谢!

服务器控制台的错误堆栈:

Started POST "/posts" for 127.0.0.1 at 2018-11-02 16:45:34 -0400
   (2.6ms)  SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
  ↳ /Users/nikhilsamuel/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
Processing by PostsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"6zdP1vkLjn0BKq4/3qFqozrUhHepyW68Kc+dcJyc4wZMgCdBHBcRawLyXA+8pVnkJelurDFF72O5eruqxujQGw==", "post"=>{"title"=>"hello there", "body"=>"app"}, "commit"=>"Create Post"}
   (0.1ms)  begin transaction
  ↳ app/controllers/posts_controller.rb:31
  Post Create (2.7ms)  INSERT INTO "posts" ("title", "body", "created_at", "updated_at") VALUES (?, ?, ?, ?)  [["title", "hello there"], ["body", "app"], ["created_at", "2018-11-02 20:45:35.246718"], ["updated_at", "2018-11-02 20:45:35.246718"]]
  ↳ app/controllers/posts_controller.rb:31
   (3.4ms)  commit transaction
  ↳ app/controllers/posts_controller.rb:31
Redirected to http://localhost:3000/posts/12
Completed 302 Found in 30ms (ActiveRecord: 7.3ms)


Started GET "/posts/12" for 127.0.0.1 at 2018-11-02 16:45:35 -0400
Processing by PostsController#show as HTML
  Parameters: {"id"=>"12"}
  Post Load (0.3ms)  SELECT  "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ?  [["id", 12], ["LIMIT", 1]]
  ↳ app/controllers/posts_controller.rb:68
  Rendering posts/show.html.erb within layouts/application
  Rendered posts/show.html.erb within layouts/application (4.2ms)
Completed 500 Internal Server Error in 633ms (ActiveRecord: 0.3ms)



ActionView::Template::Error (undefined method `each' for nil:NilClass):
    19:
    20:       <ul>
    21:         <li class="category">Notes</li>
    22:         <% @posts.each do |post| %>
    23:           <li><%= post.title %></li>
    24:         <% end %>
    25:       </ul>

app/views/layouts/application.html.erb:22:in `_app_views_layouts_application_html_erb__3194645343067756970_70256024775560'
Started GET "/posts/new" for 127.0.0.1 at 2018-11-02 16:45:40 -0400
Processing by PostsController#new as HTML
  Rendering posts/new.html.erb within layouts/application
  Rendered posts/_form.html.erb (30.6ms)
  Rendered posts/new.html.erb within layouts/application (37.1ms)
  Post Load (0.4ms)  SELECT "posts".* FROM "posts" ORDER BY created_at DESC
  ↳ app/views/layouts/application.html.erb:22
Completed 200 OK in 84ms (Views: 73.9ms | ActiveRecord: 0.4ms)


Started GET "/posts/new" for 127.0.0.1 at 2018-11-02 16:45:41 -0400
Processing by PostsController#new as HTML
  Rendering posts/new.html.erb within layouts/application
  Rendered posts/_form.html.erb (1.9ms)
  Rendered posts/new.html.erb within layouts/application (5.0ms)
  Post Load (0.2ms)  SELECT "posts".* FROM "posts" ORDER BY created_at DESC
  ↳ app/views/layouts/application.html.erb:22
Completed 200 OK in 45ms (Views: 39.1ms | ActiveRecord: 0.2ms)

标签: ruby-on-railsruby-on-rails-5

解决方案


不要依赖应用程序布局中的实例变量,这根本不应该这样做。

而是添加一个辅助方法,例如posts_for_navigation,到您的ApplicationHelper并从那里获取帖子。这将意味着控制器中的代码要少得多。


推荐阅读