2016-05-18 18 views
0

別のコントローラの新しいインスタンス内のDeviseのcurrent_user変数にアクセスしようとしています。ここでGetsInterfaceController別のコントローラのcurrent_user変数へのアクセス

class GetsInterfaceController < ApplicationController 
    def select_current_signed_in_user 
    @signed_in_user_here = current_user 
    end 
end 

の私の定義はあるそれから私は

class ClientsController < ApplicationController 
    def get_current_user 
    @gets_interface_controller = GetsInterfaceController.new 
    find_signed_in_user = @gets_interface_controller.select_current_signed_in_user 
    end 
end 

ClientsController

にGetsInterfaceControllerの新しいインスタンスをインスタンス化しかし、私はこれをしようとすると、私はGetsInterfaceControllerで@signed_in_user_here = CURRENT_USERライン上のヌルエラーを取得します。とにかく、内部のGetsInterfaceControllerからcurrent_user属性にアクセスするには?

+1

'ClientsController'から' current_user'にアクセスすることもできます。 – Uzbekjon

+2

あなたはそのようなことをする必要はありません。すべてのビュー/コントローラでcurrent_userにアクセスできます。 – toddmetheny

答えて

0

current_userは変数ではなく、ヘルパーメソッドです。したがって、すべてのヘルパーとビューですべて利用可能です。

さらにはRailsでコントローラをインスタンス化しません。ルーターがあなたのためにそれを行います。

コントローラ内の唯一のパブリックメソッドは、HTTP要求に応答するアクションである必要があります。

複数のコントローラでメソッドを再利用する場合は、継承、モジュール(懸念事項)またはヘルパーを使用する必要があります。別のコントローラでメソッドを呼び出すことは決してしないでください。


あなたはAPIクライアントクラスを作成する外部サービスを呼び出すために:あなたは、外部サービスを呼び出し、例えばデータサービスオブジェクトをいくつかのモデルを作成する必要がある場合

# adapted from https://github.com/jnunemaker/httparty 
require 'httparty' 
class StackExchangeClient 
    include HTTParty 
    base_uri 'api.stackexchange.com' 

    def initialize(service, page, user = nil) 
    @user = user 
    @options = { query: {site: service, page: page} } 
    end 

    def questions 
    self.class.get("/2.2/questions", @options) 
    end 

    def users 
    self.class.get("/2.2/users", @options) 
    end 
end 

かを:

class SomeService 
    def initialize(user, client: SomeClient) 
    @user = user 
    @client = client # for mocking 
    end 

    def call 
    response = @client.get('/foo') 
    response.each do |d| 
     @user.baz << d[:woo] 
    end 
    end 
end 

SomeService.new(current_user).call 
+0

私はそれを理解しています。これは特別なケースです。これはルーテッドコントローラではありません。これは、アプリケーション外の別のリソースをREST APIサービスに呼び出しているときに使用するクラスです。 – user1570144

+0

これをサービスオブジェクトにして、それを現在のユーザーに渡したいとします.ApplicationControllerから継承しないでください。コントローラは要求とENVを渡す必要があります。 https://blog.engineyard.com/2014/keeping-your-rails-controllers-dry-with-services – max

+0

このクラスをコントローラにしようとしましたが、それへのルートはありません。 – Kevin

0

私はコードをlibディレクトリのモジュールに移動することでこれを解決しました。魅力のように動作します

関連する問題