0

应用程序控制器有一个辅助方法: current_user 可以从我的所有视图中访问。但 pro_user 在我看来是完全无法访问的。

    def current_user
      @current_user ||= User.find_by_auth_token( cookies[:auth_token]) if cookies[:auth_token]
      rescue ActiveRecord::RecordNotFound
    end
    helper_method :current_user

   def pro_user

        @pro_user ||= Subscription.where(:email => current_user.email).pluck(:email) 
        return @pro_user
        rescue ActiveRecord::RecordNotFound

   end
   helper_method :pro_user 

现在在视图中,如果我访问 pro_user,它总是为零。但有趣的是,我在应用程序控制器中也有一个名为 current_user 的方法,它是一个 helper_method。它在视图中工作正常。

请问你能帮我吗?

4

1 回答 1

3

Your'e misdiagnosing your problem. It's working just fine, and the view can definitely see your method, but your method is returning nil. Your method isn't returning anything.

If the method actually weren't accessible, you'd see an exception to that effect. Ruby doesn't simply resolve unknown methods to nil.

In the view I was trying to see if pro_user.email.blank? and its nil all the time.

That isn't a valid way of using the value returned by the method you posted. It returns an array.

I also tried @pro_user in the view. Everything prints correctly in the application controller but its nil in the view.

Neither is that. The method returns an array of zero or more email addresses, this is what pluck does is for. The return value will never respond to .email. You would need to use pro_email.any? to test whether the array contains any items.

You also can't simply access @pro_user. That doesn't invoke the method, that access a member variable which will be nil by default.

I do <% if pro_user.blank? %> { ..do blah.. }

That's not valid erb syntax. Assuming that your syntax is actually correct, blank? will return true for an empty array. The method is returning [], not nil. There is no error, you just need to figure out why your query returns zero records.

于 2014-04-30T21:12:23.160 回答