I am using devise omniauth in my rails application, here is the User class
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :omniauthable
attr_accessible :email, :password, :password_confirmation, :remember_me, :encrypted_password, :fb_id
def set_facebook_info(info)
@facebook_info = info
end
def get_facebook_info
@facebook_info
end
def self.find_for_facebook_oauth(access_token, signed_in_resource=nil)
data = access_token.extra.raw_info
if user = User.find_by_email(data.email)
if not user.fb_id
user.fb_id = access_token.uid
user.save
end
user.set_facebook_info "whatever" <-- I tried here
user
else # Create a user with a stub password.
user = User.create(:email => data.email, :password => Devise.friendly_token[0,20], :fb_id => access_token.uid)
user
end
end
def self.new_with_session(params, session)
super.tap do |user|
user.set_facebook_info "whatever" # <-- I Tried here too
if data = session["devise.facebook_data"] && session["devise.facebook_data"]["extra"]["user_hash"]
user.email = data["email"]
end
end
end
end
I want to use set and get methods for keeping some facebook user information. but when I use current_user in view, it gives me no value of what I’ve set in my User class.
like in application.html.erb :
<span><%= current_user.get_facebook_info %></span>
returns an empty value
Does anybody has an idea about it ? It should be a common case. in general , how can we assign some non connected to DB attribute to current_user via devise ?
Thanks
Your @facebook_info attribute is only stored in memory, not persisted to the database. So on the next page load, Devise is going to load your model from the database again, and that is why the information is missing.
If you want to keep the Facebook info, you need to persist it to the database. Rails has some nice ways of storing hashes directly in a text column:
Source: http://api.rubyonrails.org/classes/ActiveRecord/Base.html