Why ActiveModel::ForbiddenAttributesError error?

425 Views Asked by At

Here's my model

class User < ActiveRecord::Base
  def self.from_omniauth(auth)
    where(auth.slice(:provider, :uid)).first_or_initialize.tap do |user|
      user.provider = auth.provider
      user.uid = auth.uid
      user.name = auth.info.name
      user.oauth_token = auth.credentials.token
      user.oauth_expires_at = Time.at(auth.credentials.expires_at)
      user.save!
    end
  end
end

Here's my controller

class SessionsController < ApplicationController
  def create
    user = User.from_omniauth(env["omniauth.auth"])
    session[:user_id] = user.id
    redirect_to root_url
  end

 def destroy
   session[:user_id] = nil
   redirect_to root_url
 end
 end

I tried looking into the database if any duplicate entry has been made. But no. Please let me know if you can help.

1

There are 1 best solutions below

0
On

Just change the where(condition) to:

where(provider: auth.provider, uid: auth.uid)

The 1st approach fails because of the method #permitted? which AR calls (if defined) to sanitize the attributes.

> h = auth.slice(:provider, :uid)
> h.class
=> OmniAuth::AuthHash < Hashie::Mash
> h.permmitted?
> false

However, a simple Hash will not have #permitted? defined, thus it will just continue:

> h = { provider: auth.provider, uid: auth.uid }
> h2.permitted?
NoMethodError: undefined method `permitted?' for {:provider=>"facebook", :uid=>"XXXX"}:Hash

Reference: https://github.com/rails/rails/blob/master/activemodel/lib/active_model/forbidden_attributes_protection.rb#L19)