Can Rails可以区分参数类型吗?

时间:2013-09-02 01:37:47

标签: ruby-on-rails ruby-on-rails-3 routing

假设我有这样的路线:

get 'share/:ftp/:id' => 'share#show', :as => :share

我可以让Rails识别用户是否输入了:id或其他不同类型的变量吗?因此,如果用户在其中键入某个字符串,则会根据该字符串查找记录?像这样的东西(伪代码):

get 'share/:ftp/:id || share/:ftp/:string' => 'share#show', :as => :share

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

要在路线中允许ID或字符串,您不需要在路线上进行更改,只需使用更灵活的find替代方法。

# routes.rb
get 'share/:ftp/:id' => 'share#show', :as => :share # No change.

# ShareController
@share = Share.find_param(params[:id]) # Call a custom method

# Share model
# Suppose your "string" is the name
class Share < ActiveRecord::Base
  def self.find_param(input, param='name')
    input.to_i == 0 ? send("find_by_#{param}" : super
  end
end

答案 1 :(得分:0)

除非您指定约束,否则Rails将接受任何类型作为参数。格式约束看起来像get '/:id', to: 'posts#show', constraints: {id: /^\d/}有关约束的更多信息http://guides.rubyonrails.org/routing.html#segment-constraints