简体   繁体   中英

Polymorphic Routes in Rails - in views

I have Comment as a polymorphic model.

It is attached to Post, Review, etc.

I also have an action in CommentsController, called test .

I have my routes setup, so test_post_comment_path works (to call the test action in the CommentsController).

The problem is, in my partial view, I want that route to be able to change, based on the current action, ie. it is test_post_comment_path when on a Post and test_review_comment_path when on a Review.

正确的方法是使用polymorphic_url ...

Just use two different paths?

What I mean is: you don't want to put so much logic inside routes.

If routes try to do something more than routing, the first time somethings goes wrong you'll be in serious trouble.

In your partial view, the logic to create specific links or other html comment stuff should go in a helper.

Something like this: (in your partial view)

@commentable.each |commentable|
    test_#{commentable.class.to_s.downcase}_comment_path
end

if it is 'post' then it will generate 'test_post_comment_path', if it is review, it will generate test_review_comment_path

我决定根据当前操作是否存在,在视图中使用if语句,例如@post或@review

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