Best practices to handle routes for STI subclasses in rails

后端 未结 18 1306
面向向阳花
面向向阳花 2020-11-30 16:25

My Rails views and controllers are littered with redirect_to, link_to, and form_for method calls. Sometimes link_to and <

18条回答
  •  半阙折子戏
    2020-11-30 17:15

    I'm in favor of using PolymorphicRoutes or url_for to dynamically generate routes based on the resource, any namespace, etc.

    https://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html

    https://api.rubyonrails.org/classes/ActionDispatch/Routing/UrlFor.html

    polymorphic_url([:admin, @article, @comment])
    # => admin_article_comment_url(@article, @comment)
    
    edit_polymorphic_path(@post) 
    # => "/posts/1/edit"
    

    With admin namespace

    url_for([:admin, Role])
    # => "admin/roles" # index
    
    url_for([:admin, Role, action: :new])
    # => "admin/roles/new" # new
    
    url_for([:admin, @role])
    # => "admin/roles/1" # show; for destroy, use link "method: :delete"
    
    url_for([:edit, :admin, @role])
    # => "admin/roles/1/edit" # edit
    

提交回复
热议问题