如何路由到新的rails控制器操作

时间:2012-08-03 05:38:48

标签: ruby-on-rails routing routes

我是Rails的新手,遇到了这个问题。

我有一个books_controller,我在其中定义了一个名为download的新动作:

def download
  @book = Book.find(params[:id])

  return send_file @book.get_filepath, :type => 'application/pdf', :filename => @book.get_filename
end

我的routes.rb就像:

resources :books
match '/books(/download(/:id))', :controller => "books", :action => "download"

我想创建一个像/ books / download / 10这样的URL来调用下载操作。

我不确定如何创建该链接。我试过在路由上阅读Rails指南,但我很困惑。

我试过了

<td><%= link_to books_download_path(book) %></td>

它显然不起作用。

undefined method `books_download_path' for #<#<Class:0x682ac40>:0x482cad8>

我很感激你的帮助。

由于

P.S。也许/ books / 10 / download比/ books / download / 10

更有意义

index.html.erb

<table>
<% @recent_books.each do |book| %>
    <tr>
        <!-- <td><%= image_tag(book.get_thumbnail) %></td> -->
        <td><%= truncate(book.get_title, :length => 30) %></td>
        <td><%= book.get_author %></td>
        <td><%= book.get_summary %></td>
        <td><%= truncate(book.get_filename, :length => 30) %></td>
        <!-- <td><%= link_to 'Download', book %></td> -->
        <td><%= link_to "Download", download_book_path(book) %></td>
    </tr>
<% end %>
<table>

的routes.rb

Caliberator :: Application.routes.draw做     资源:作者

resources :books do
  get :download, :on => :member, :to => 'books#download'
end

4 个答案:

答案 0 :(得分:2)

对于Rails 3,试试这个

resources :books do
  get :download, :on => :member, :to => 'books#download'
end

现在,在您的观看中,您可以使用。

<%= link_to 'Download', download_book_path(book) %>

这将生成books/10/download类型链接。

答案 1 :(得分:0)

尝试以下

match '/books(/download(/:id))', :controller => "books", :action => "download", :as => "books_download"

参考: - naming_routes

答案 2 :(得分:0)

你必须这样做:

<%= link_to "Download", download_books_path + "/#{book.id}" %>

答案 3 :(得分:0)

对于rails 3,你应该写:

resources :books do
  member do
    get 'download'
  end
end