ruby-on-rails - 向 rails 路由资源添加额外的参数

标签 ruby-on-rails resources routing

我想做的事情看起来很简单,但可能并不“正确”

假设我有一个图像资源,我根据 url 操作图像。在 url 中,我想指定它的大小,以及它是变灰、着色、变暗还是其他一些条件。

目前我有许多类似这样的命名路线。

map.gray_product_image "images/:product/:image/gray/:size.:format", :controller => 'images', :action => 'gray_product_image'

对我来说,诀窍是,如果我使用 Rails 资源创建它,我不知道如何指定 :size、:format 或“颜色类型”。

我想我想添加一个成员路由并指定我的参数,如下所示。
map.resources :products do |products| 
  products.resources :images, :member => {:gray_product_image => {':image/:size.:format' => :get}}
end

有时我想向资源路由添加额外信息,但不知道如何添加。

任何帮助将不胜感激,
谢谢。

最佳答案

没有删除资源的 Controller /id 部分的好方法。最接近你将通过使用这样的东西来欺骗 ActionController 的方法:

map.resources :gray, :path_prefix => "/images/:product/:image_id/", 
  :controller => 'images', :requirements => {:colour => "gray"}

这将产生像 www.site.com/images/product/4/gray/1234.html 这样的路由使用以下参数散列:
params => { 
  :image_id => 4,
  :id => 1234,
  :colour => "gray",
  :product => "product"
}

格式不会被明确传递,但它会通过通常的 respond_to 手段在 Controller 中可用。

接下来,您必须在 Controller 中使用一些魔法来诱使 Rails 执行您想要的操作。
class ImagesController < ApplicationController
  def show
    @size = params[:id]
    @image = Image.find(params[:image_id])
    ...
  end
end

这实际上作为过滤器效果更好,因此:
class ImagesController < ApplicationController
  def initialize_colour
    unless params[:colour].nil?
      @size = params[:id]
      @colour = params[:colour]
      @image = Image.find(params[:image_id])
    end
  end

  before_filter :initialize_colour, :except => [:index, :new, :create]

  ...

end

但是,要充分利用这些路由,您必须将所有这些额外参数传递给您的 url 以进行调用。像这样:
gray_url(size, :image_id => @image.id, :product => product)

但是助手让这变得容易。
module ApplicationHelper
  def easy_gray_url(image, size, product)
    gray_url(size, :image_id => image.id, :product => product)
  end
end

关于ruby-on-rails - 向 rails 路由资源添加额外的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1732564/

相关文章:

java - 从类路径目录中获取资源列表

c# - 无法更改 .aspx 页面的区域性

c# - 如何检查 RedirectToRouteResult 生成的 URL?

ruby-on-rails - rails 3 + 设计 : on after_inactive_sign_up_path_for() how show the not-yet-confirmed user's email address?

ruby-on-rails - 如何将 "import"嵌套类放入 Ruby 中的当前类?

java - 在 Java 中,如何在 Web 应用程序中动态重新加载资源包?

angular - 从 Angular 5 中的 URL 获取数据

ruby-on-rails - rails : Why "has_many ..., :through => ..." association results in "NameError: uninitialized constant ..."

ruby-on-rails - 在 Ruby 中获取 URL 的重定向

url - Symfony2 - 每个地区的网址