【问题标题】:Passing objects as an argument for a path helper将对象作为路径助手的参数传递
【发布时间】:2013-07-10 21:13:53
【问题描述】:

假设我有一条路线get "/:year/:month/:slug", :as => :post"。为了使它工作,我已经在Post 类中添加了以下方法:

def to_param
  slug
end

现在,如果我想使用 post_path 路由助手,我必须向它传递 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_path(@post.uri) 来获取路径。但这仍然不是我想要的。我想要的是能够在那里传递一个对象,比如post_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>}

可以很容易地推断,Rails 的真正作用类似于:post_path({ year: @post }),这显然是错误的。然而,Rails 生成的默认路由仅使用:id 作为参数,在将对象传递给它之后工作。 Rails 在内部是如何做到的?它是否在Post 上使用了任何需要重载的隐藏方法? (我尝试过to_s、url_options、id 等,但都没有成功。)

长话短说

在将@post 传递给post_path(而不是@post.special_method)之后,Rails 会看到一个哈希{ year: ..., month: ..., slug: ...}?

编辑:

来自 routes.rb 文件的摘录:

scope ':year/:month', :constraints => { year: /\d{4}/, month: /\d{2}/ } do
  scope ':slug', :constraints => { slug: /[a-z0-9-]+/ } do
    get '/' => 'posts#show', :as => :post
    put '/' => 'posts#update'
    delete '/' => 'posts#destroy'
    get '/edit' => 'posts#edit', :as => :edit_post
  end
end

get 'posts' => 'posts#index', :as => :posts
post 'posts' => 'posts#create'
get 'posts/new' => 'posts#new', :as => :new_post

也许会有所帮助。

【问题讨论】:

    标签: ruby-on-rails ruby routes


    【解决方案1】:

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

    def to_param
      { year: self.published_at.strftime('%Y'), month: self.published_at.strftime('%m'), slug: self.slug }
    end
    

    根据 Rails APIdock,url_for 方法在传入的对象上调用 to_param,默认为 id。

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

    您可以参考this apidock link了解更多信息

    【讨论】:

    • 无论to_param 返回什么,仍然返回相同的错误。在我的情况下,似乎 Rails 根本不使用to_param。也许是因为我没有在 routes.rb 文件中使用resources?我已经编辑了我的问题以包含它。
    猜你喜欢
    • 2013-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多