2013-12-19 153 views
0

我是rails新手。我用控制器products_controller.rb创建了一个演示项目,当我输入这个url http://localhost:3000/products时,我可以看到数据库中现有产品的列表。但是我需要创建一个名为“display”的新页面,并且我的产品应该显示的网址应该是http://localhost:3000/products/display。我怎样才能做到这一点?如何显示一个页面的内容到另一个页面的内容

回答

0

你可能寻找Rails的RESTful routing structure

每次你在你的routes文件中使用resources :controller时间,它创建7 routes for that controller

  • 指数
  • 创建
  • 编辑
  • 更新
  • 显示
  • 销毁

对我来说,似乎你试图使用show方法:


显示

Rails的show方法基本上显示在页面上特定的对象,像这样:

/products/234 

这显示自身

你的代码这个问题的方法的产品是非常简单的:

#app/controllers/products_controller.rb 
def show 
    @product = Product.find(params[:id]) 
end 

您可以通过以下链接与URL helper

<%= link_to "View", products_path(product.id) %> 

这将允许你展示你点击的产品

1

如果你想使用一个辅助作用,而不只是一个不同的路径索引操作,你需要收集自定义操作:

在你的routes.rb

resources :products do 
    collection do 
    get :display 
    end 
end 

然后在您products_controller.rb

class ProductsController 
    def display 
    @products = Product.all 
    end 
end 

,然后创建一个display.html.erb/HAML/...在你的应用程序/视图/产品目录并填写任何你想要的:-)

如果您只是想要一个到索引操作的不同路径,您可以添加一个自定义路径。路由指南解释这更好然后我可以,所以我只是链接到它:http://guides.rubyonrails.org/routing.html

1

我想你只想为产品的索引页面定制一个url。

可以实现在以下way-

在你的routes.rb

get "/products/display" => "products#index" 
resources :products 

只记得把你的资源自定义路由条目下。

我希望这可以帮助你!

相关问题