2016-03-04 182 views
0

问题,所以我是新手到rails,目前正在通过tutorialspoint它的教程。到目前为止,我得到的是一个控制器和一个相应的视图,它是一个erb文件。这是视图代码:Rails与渲染

<% 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> 

然而,当我尝试查看这个通过本地主机:3000,同时具有在本地主机后台运行的WEBrick服务器

rails server 

命令:3000, 它使指挥我在我的浏览器,这是由服务器从以下路径呈现的默认视图:

/Users/hassanali/.rbenv/versions/2.2.3/lib/ruby/gems/2.2 0.0 /宝石/ railties-4.2.4/lib目录/轨/模板/导轨/首页/ index.htm的l.erb

,而不是我的Rails应用程序文件夹的视图folder..which内的实际看法是

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

我一直在试图解决这个问题,现在已经很久没有用了。有谁知道我能做什么?

回答

4

因为您没有为您的应用定义root_path。通过使用root controller#action

root 'book#list' 
+0

干杯!工作! :) –

2

你可以告诉Rails你想 '/' 路由什么:

config/routes.rb定义root_path吧,恩。

例如说你有一个看起来像这样的控制器。

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指南的路由,所以你了解你的选择。