【问题标题】:Why ActiveModel::ForbiddenAttributesError error?为什么 ActiveModel::ForbiddenAttributesError 错误?
【发布时间】:2015-07-27 09:03:20
【问题描述】:

这是我的模型

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

这是我的控制器

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

如果有任何重复条目,我尝试查看数据库。但不是。如果您能提供帮助,请告诉我。

【问题讨论】:

  • 请添加您的服务器日志。这样可以更具体地解释您的问题
  • 我克服了这个问题。现在它说用户表不存在。 @Rubyrider
  • 那么您不知何故进行了此类操作,或者您的数据库已被移走。请运行迁移或查看是否需要再次运行 rake db:setup。

标签: ruby-on-rails sqlite omniauth omniauth-facebook


【解决方案1】:

只需将 where(condition) 更改为:

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

第一种方法因方法#permitted 而失败?哪个 AR 调用(如果已定义)来清理属性。

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

然而,一个简单的哈希不会有#permitted?已定义,因此它将继续:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多