Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/59.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails可以区分不同类型的参数吗?_Ruby On Rails_Ruby On Rails 3_Routing - Fatal编程技术网

Ruby on rails Rails可以区分不同类型的参数吗?

Ruby on rails Rails可以区分不同类型的参数吗?,ruby-on-rails,ruby-on-rails-3,routing,Ruby On Rails,Ruby On Rails 3,Routing,假设我有一条这样的路线: get 'share/:ftp/:id' => 'share#show', :as => :share 我可以让Rails识别用户是否键入了:id或其他不同类型的变量吗?那么,如果用户在其中键入某个字符串,它将根据该字符串查找记录?类似这样的内容(伪代码): 感谢您的帮助。若要允许在路由中使用id或字符串,您不需要更改路由,只需使用比查找更灵活的替代方法即可 # routes.rb get 'share/:ftp/:id' => 'share#sho

假设我有一条这样的路线:

get 'share/:ftp/:id' => 'share#show', :as => :share
我可以让Rails识别用户是否键入了
:id
或其他不同类型的变量吗?那么,如果用户在其中键入某个字符串,它将根据该字符串查找记录?类似这样的内容(伪代码):


感谢您的帮助。

若要允许在路由中使用id或字符串,您不需要更改路由,只需使用比
查找
更灵活的替代方法即可

# 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
#routes.rb
获取'share/:ftp/:id'=>'share#show',:as=>:share#无更改。
#共享控制器
@share=share.find_param(params[:id])#调用自定义方法
#共享模型
#假设您的“字符串”是名称
类共享
若要在路由中允许id或字符串,您不需要更改路由,只需使用一种更灵活的替代方法来查找

# 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
#routes.rb
获取'share/:ftp/:id'=>'share#show',:as=>:share#无更改。
#共享控制器
@share=share.find_param(params[:id])#调用自定义方法
#共享模型
#假设您的“字符串”是名称
类共享
除非指定约束,否则Rails将接受任何类型作为参数。格式约束类似于
get'/:id',to:'posts#show',约束:{id://^\d/}
此处有关约束的详细信息

除非指定约束,否则Rails将接受任何类型作为参数。格式约束类似于
get'/:id',to:'posts#show',约束:{id://^\d/}
这里有更多关于约束的信息

您需要的似乎是路由约束。检查:Rails已经完成了这项工作。
:id
基本上可以匹配任何内容。您需要的似乎是路由约束。检查:Rails已经完成了这项工作。
:id
基本上可以匹配任何内容。哦,哈:应该是
.Ah,是的,
to_i
,输入太快请不要覆盖Active Record中的
find
,因为您正在覆盖其他代码可能依赖的非常基本的功能。相反,请将此方法称为不同的方法。@RyanBigg,很好的建议,我接受。我以前读过您的第一版书,只知道第二版即将到来g、 等不及看了!很高兴听到,@BillyChan:)哦,哈:应该是
to_i
。啊,是的,
to_i
,打字太快了。请不要覆盖活动记录中的
查找
,因为你覆盖了其他代码可能依赖的非常基本的功能。相反,把这个方法称为不同的方法。@RyanBigg,很好的建议,我接受。我以前读过你的第一版书知道第二次就要来了,迫不及待地想读到它!很高兴听到,@BillyChan:)