Brian
Brian

Reputation:

Accessing a variable declared in a controller from a model

I'm using the facebooker gem which creates a variable called facebook_session in the controller scope (meaning when I can call facebook_session.user.name from the userscontroller section its okay). However when I'm rewriting the full_name function (located in my model) i can't access the facebook_session variable.

Upvotes: 0

Views: 98

Answers (1)

austinfromboston
austinfromboston

Reputation: 3780

You'll have to pass the value into your model at some point, then store it if you need to access it regularly.
Models aren't allowed to pull data from controllers -- it would break things in console view, unit testing and in a few other situations.

The simplest answer is something like this:

class User
    attr_accessor :facebook_name
    before_create :update_full_name

    def calculated_full_name
       facebook_name || "not sure"
    end

    def update_full_name
       full_name ||= calculated_full_name
    end
end


class UsersController
    def create
       @user = User.new params[:user]
       @user.facebook_name = facebook_session.user.name

       @user.save
    end
end

Upvotes: 1

Related Questions