简体   繁体   中英

Polymorphic Routes in Rails 4.1.4

I have a polymorphic association between Posts and Postables, right now with Projects being my only Postables. In my routes, I have:

resources :projects do
  ...

  member do
    resources :posts
  end
end

I know how to retrieve the right ids from the parameters, and all of my controller specs pass just fine, but when I try to write links in my views, they don't work. Running rake routes , I see a little weirdness:

...

post SHOW      /projects/:id/posts/:id(.:format)    posts#edit

...

And so on for the rest. If I'm not mistaken, the path should be 'new_project_post', and the first parameter should be :project_id .

Now, in my show view for Projects, I have the index of posts for that particular project. But the links don't work. Lets assume I have a project with an ID of 2, and a post for that project with an ID of 1.

If I try link_to 'Edit', edit_post_path(@project, post) , the link comes out as .../projects/1/posts/1/edit , so both :id s get the post's id. If I swap post and @project , both :id s will be the project's id.

If I try passing them as an array, link_to 'Edit', post_path([post, @project]) , the resulting link will be .../projects/1%2F2/posts/1%2F2/edit . %2F is a URL-encoded slash character, so I'm not sure what the hell Rails is trying to do here.

If I try using polymorphic_path([@project, post]) for my links, all it does is spit out paths that don't exist: undefined method 'project_post_path'

I've tried several other combinations of parameters without success. So if anyone could point me in the right direction, I'd be extremely grateful.

The appropriate syntax for nested resources in Rails is:

resources :projects do
  resources :posts
end

In member block you could only declare additional actions to work with project instances.

You are using nested resource inside member and it is incorrect. Read more about this here: http://thelazylog.com/posts/polymorphic-routes-in-rails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM