开发者

Rails 3 routes with non-numeric id's

I have an object that by necessity has an id that looks something like "1.3.6.1.4.1.25623.1.0.14377". When I try to create a link that uses the i开发者_StackOverflow社区d (such as link_to my_object(object.id)), Rails 3 barfs and says that no route exists.

I have verified that I have a valid route in place by trying link_to my_object(1). Rails doesn't have a problem with creating this link.

Any ideas?

Thanks in advance!


I've figured it out... By default, Rails freaks when a period (.) is found in a parameter field (in this case id). To change this behavior, simply add a :constraints directive to your route statement and tell it explicitly what the parameter should look like. In my case it turned out that the following fixed the problem:

resources :nvts, :constraints => { :id => /[0-9\.]+/ }

Thanks to Avdi Grimm for his most helpful blog post.


Maybe you should override in your model the method to_param, Rails uses it to generate id for routing. Usually it looks like this:

def to_param
  object.parameterize
end

It gets the model's name and use as id in route.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜