Ruby on rails 将对象作为路径辅助对象的参数传递

Ruby on rails 将对象作为路径辅助对象的参数传递,ruby-on-rails,ruby,routes,Ruby On Rails,Ruby,Routes,假设我有一个routeget/:year/:month/:slug“,:as=>:post”。为了使它起作用,我已经在post类中添加了以下方法: def to_param slug end 现在,如果我想使用post_pathroute helper,我必须向它传递3个参数,比如:post_path({year:'2013',month:'07',slug:'lorem ipsum'}),但由于我不喜欢每次都编写它,我添加了另一个方法: def uri { year: self.pu

假设我有一个route
get/:year/:month/:slug“,:as=>:post”
。为了使它起作用,我已经在
post
类中添加了以下方法:

def to_param
  slug
end
现在,如果我想使用
post_path
route helper,我必须向它传递3个参数,比如:
post_path({year:'2013',month:'07',slug:'lorem ipsum'})
,但由于我不喜欢每次都编写它,我添加了另一个方法:

def uri
  { year: self.published_at.strftime('%Y'), month: self.published_at.strftime('%m'), slug: self.slug }
end
它允许我使用
post\u path(@post.uri)
来获取路径。但这仍然不是我想要的。我想要的是能够在那里传递对象,比如
post\u path(@post)
,这给了我以下错误:

ActionController::RoutingError: No route matches {:controller=>"posts", :action=>"show", :year=>#<Post id: nil, slug: "lorem-ipsum", title: nil, body: nil, published: nil, published_at: nil, created_at: nil, updated_at: nil>}

也许会有帮助。

尝试将uri方法中的代码移动到_param

def to_param
  { year: self.published_at.strftime('%Y'), month: self.published_at.strftime('%m'), slug: self.slug }
end
根据Rails APidock,url_用于对传入对象(默认为id)上的_参数进行方法调用

<%= url_for(@workshop) %>
# calls @workshop.to_param which by default returns the id
# => /workshops/5

#调用@workshop.to_param,默认情况下返回id
#=>/workshops/5

您可以参考以了解更多信息

仍然返回相同的错误,无论
to_param
返回什么。在我的情况下,Rails似乎根本不使用
to_param
。可能是因为我没有在routes.rb文件中使用
资源
?我也编辑了我的问题以包含它。
<%= url_for(@workshop) %>
# calls @workshop.to_param which by default returns the id
# => /workshops/5