My helper methods in controller

后端 未结 3 461
难免孤独
难免孤独 2021-01-02 08:57

My app should render html, to answer when a user clicks ajax-link.

My controller:

def create_user
  @user = User.new(params)
  if @user.save
    stat         


        
相关标签:
3条回答
  • 2021-01-02 09:16

    helpers are just ruby modules which you can include in any controller just like any module.

    module UserHelper
        def link_to_profile(user)
            link = link_to(user.login, {:controller => "users", :action => "profile", :id => user.login}, :class => "profile-link")
            return(image_tag("/images/users/profile.png") + " " + link)
        end
    end
    

    And, in your controller :

    class UserController < ApplicationController
        include UserHelper
    
        def create
            redirect_to link_to_profile(User.first)
        end
    end
    
    0 讨论(0)
  • 2021-01-02 09:22

    Take that! http://apotomo.de/2010/04/activehelper-rails-is-no-pain-in-the-ass/

    That's exactly what you were looking for, dude.

    0 讨论(0)
  • 2021-01-02 09:35

    Oki. Let's recap. You want access to certaint functions/methods, but you don't want those methods to be attached to current object.

    So you want to make a proxy object, that will proxy/delegate to those methods.

    class Helper
      class << self
       #include Singleton - no need to do this, class objects are singletons
       include ApplicationHelper
       include ActionView::Helpers::TextHelper
       include ActionView::Helpers::UrlHelper
       include ApplicationHelper
      end
    end
    

    And, in controller:

    class UserController < ApplicationController
      def your_method
        Helper.link_to_profile
      end
    end
    

    The main disadvantage to this approach is that from the helper functions you won't have access to controller context (EG you won't have access to params, session, etc)

    A compromise would be to declare those functions as private in the helper module, therefore, when you will include the module, they will also be private in the controller class.

    module ApplicationHelper
      private
      def link_to_profile
      end
    end
    
    class UserController < ApplicationController
      include ApplicationHelper
    end
    

    , as Damien pointed out.

    Update: The reason why you get the 'url_for' error is that you do not have access to controller's context, as stated above. You could force passing the controller as a parameter(Java-style ;) ) like:

    Helper.link_to_profile(user, :controller => self)
    

    and then, in your helper:

    def link_to_profile(user, options)
      options[:controller].url_for(...)
    end
    

    or event a bigger hack, presented here. However, i would reccomend the solution with making methods private and including them in the controller.

    0 讨论(0)
提交回复
热议问题