9

私のアプリは、ユーザーが ajax-link をクリックしたときに応答するために、html をレンダリングする必要があります。

私のコントローラー:

def create_user
  @user = User.new(params)
  if @user.save
    status = 'success'
    link = link_to_profile(@user) #it's my custom helper in Application_Helper.rb
  else
    status = 'error'
    link = nil
  end

  render :json => {:status => status, :link => link}
end

私のヘルパー:

  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

私はそのような方法を試しました:

ApplicationController.helpers.link_to_profile(@user)
# It raises: NoMethodError (undefined method `url_for' for nil:NilClass)

と:

class Helper
  include Singleton
  include ActionView::Helpers::TextHelper
  include ActionView::Helpers::UrlHelper
  include ApplicationHelper
end
def help
  Helper.instance    
end

help.link_to_profile(@user)
# It also raises: NoMethodError (undefined method `url_for' for nil:NilClass)

さらに、はい、私は :helper_method について知っていますが、それは機能しますが、そのメソッドをたくさん使って ApplicationController をオーバーロードしたくありません

4

3 に答える 3

15

ヘルパーは、任意のモジュールと同様に、任意のコントローラーに含めることができる単なる Ruby モジュールです。

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

そして、コントローラーで:

class UserController < ApplicationController
    include UserHelper

    def create
        redirect_to link_to_profile(User.first)
    end
end
于 2010-04-07T08:35:16.617 に答える
13

大木。要約しましょう。特定の関数/メソッドにアクセスしたいが、それらのメソッドを現在のオブジェクトにアタッチしたくない場合。

したがって、これらのメソッドにプロキシ/デリゲートするプロキシ オブジェクトを作成する必要があります。

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

そして、コントローラーで:

class UserController < ApplicationController
  def your_method
    Helper.link_to_profile
  end
end

このアプローチの主な欠点は、ヘルパー関数からコントローラー コンテキストにアクセスできないことです (たとえば、パラメーター、セッションなどにアクセスできません)。

妥協案は、これらの関数をヘルパー モジュールでプライベートとして宣言することです。したがって、モジュールをインクルードすると、コントローラー クラスでもプライベートになります。

module ApplicationHelper
  private
  def link_to_profile
  end
end

class UserController < ApplicationController
  include ApplicationHelper
end

ダミアンが指摘したように。

更新: 上記のように、「url_for」エラーが発生する理由は、コントローラーのコンテキストにアクセスできないためです。次のように、コントローラーをパラメーター (Java スタイル ;) として強制的に渡すことができます。

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

そして、あなたのヘルパーで:

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

または、ここで提示されるより大きなハックをイベントします。ただし、メソッドをプライベートにしてコントローラーに含めることで解決策をお勧めします。

于 2010-04-07T13:38:04.310 に答える
-1

それを取ってください!http://apotomo.de/2010/04/activehelper-rails-is-no-pain-in-the-ass/

それはまさにあなたが探していたものです、おい。

于 2010-04-10T18:20:34.727 に答える