What's the correct way to run one controller action from another controller action without an HTTP redirect?

后端 未结 6 639
无人及你
无人及你 2020-12-30 09:33

I\'d like to be able to dispatch from one controller action to another conditionally, based on a combination of query parameters and data in the database.

What I hav

6条回答
  •  情深已故
    2020-12-30 09:47

    I suspect you want option 3, but lets go through the some alternatives first

    Option 1 - Push the controller selection logic into a helper that inserts the right link into your view. Benifits - controllers remain clean, Cons - if decision logic depending on submitted values this approach won't work. If URL is being called by external websites then this won't work.

    Option 2 - Push the logic back into your model. Pro's - keeps controller clean. Cons - doesn't work well if you've got lots of sesson, params or render / redirect_to interaction.

    Option 3 - Stay within the same controller. I suspect you are trying to replace some existing functionality with some new functionality, but only in some cases. Pro's - Simple and have access to everything you need. Cons - only works if it makes sense to use the same controller i.e. you're working with the same entity such as user, place or company.

    Lets look an an example for option 3. My links controller has totally diferent behavour for admins than other users ...

    class LinksController < ApplicationController
      #...
    
      def new
        #Check params and db values to make a choice here
        admin? ? new_admin : new_user
      end
    
      #...
    
    private
    
      def new_admin
        #All of the good stuff - can use params, flash, etc 
        render :action => 'new_admin'    
      end
    
      def new_user
        #All of the good stuff - can use params, flash, etc 
        render :action => 'new_user' 
      end
    
    end
    

提交回复
热议问题