【问题标题】:Rails issue with renderingRails 渲染问题
【发布时间】:2016-03-04 11:20:29
【问题描述】:

所以我是 Rails 新手,目前正在 tutorialspoint 上阅读它的教程。到目前为止,我得到的是一个控制器和一个相应的视图,它是一个 erb 文件。这是视图的代码:

<% if @books.blank? %>
<p>There are not any books currently in the system.</p>
<% else %>
<p>These are the current books in our system</p>

<ul id = "books">
   <% @books.each do |c| %>
   <li><%= link_to c.title, {:action => 'show', :id => c.id} -%></li>
   <% end %>
</ul>

<% end %>
<p><%= link_to "Add new Book", {:action => 'new' }%></p>

但是,当我尝试通过 localhost:3000 查看此内容时,

rails server

在 localhost:3000 后台运行 WEBrick 服务器的命令, 它不断将我引导到浏览器上的默认视图,该视图由服务器从以下路径呈现:

/Users/hassanali/.rbenv/versions/2.2.3/lib/ruby/gems/2.2.0/gems/railties-4.2.4/lib/rails/templates/rails/welcome/index.html.erb

而不是我的rails应用程序文件夹的视图文件夹中的实际视图..这是

/Users/hassanali/Desktop/library/app/views/book/list.html.erb

我多年来一直在尝试解决此问题,但无济于事。有谁知道我能做什么?

【问题讨论】:

    标签: ruby-on-rails view controller


    【解决方案1】:

    因为您没有为您的应用定义root_path

    config/routes.rb 中为它定义root_path,例如:

    root 'book#list'
    

    【讨论】:

    • 干杯老兄!工作! :)
    【解决方案2】:

    您可以使用root controller#action 告诉 Rails 您希望“/”路由到什么。

    例如,假设您有一个看起来像这样的控制器。

    class BooksController < ActionController::Base
      def index
        @books = Books.all
      end
    
      def show
        @book = Books.find(params[:id])
      end
    end
    

    如果您希望 '/' 路由到您的 index 方法,您可以在 config/routes.rb 中执行以下操作。

    Rails.application.routes.draw do
    
      root 'books#index'
    
      # Other routes here...
    
    end
    

    附带说明,如果您添加两个 root 方法调用,它将使用路由文件中的最后一个。

    http://guides.rubyonrails.org/routing.html#using-root

    由于您引用了 shownew 操作,因此您可能也需要这些路由。建议使用 RESTful 路由方案。 Rails 提供了一个有用的方法,称为 resources,它创建了 CRUD 资源所需的所有路由和辅助方法。

    可能如下所示。

    Rails.application.routes.draw do
    
      root 'books#index'
    
      # A books resource
      resources :books
    
    end
    

    http://guides.rubyonrails.org/routing.html#crud-verbs-and-actions

    我鼓励您阅读有关路由的 Rails 指南,以便了解您的选择。

    【讨论】:

      猜你喜欢
      • 2011-05-24
      • 1970-01-01
      • 2015-06-19
      • 1970-01-01
      • 1970-01-01
      • 2011-06-13
      • 2014-03-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多