3

route があるとしましょう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どれも機能しませんでした。)

簡単に言えば

Rails が(eg ではなく){ year: ..., month: ..., slug: ...}に渡し@postた後にハッシュを確認するにはどうすればよいですか?post_path@post.special_method

編集:

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

多分それは助けになるでしょう。

4

1 に答える 1