RT,学习@Terry老师在http://railscasts-china.com 的视频教程时,我电脑使用的 rails 版本:
rails -v
:Rails 3.2.6
,每次生产一个 model 时。都会在 model 中自动加上 attr_accessible,现在用 omniauth 时,出现了这个问题,代码是这样的,
class User < ActiveRecord::Base
attr_accessible :email, :nickname
validates :nickname, :presence => true
validates :email, :presence => true, :uniqueness => true
has_many :authentications
has_many :posts
accepts_nested_attributes_for :authentications
def add_auth(auth)
authentications.create(:provider => auth[:provider],
:uid => auth[:uid])
end
class << self
def from_auth(auth)
locate_auth(auth) || locate_email(auth) || create_auth(auth)
end
def locate_auth(auth)
Authentication.find_by_provider_and_uid(auth[:provider],
auth[:uid]).try(:user)
end
def locate_email(auth)
user = find_by_email(auth[:info][:email])
return unless user
user.add_auth(auth)
user
end
def create_auth(auth)
create!(
:nickname => auth[:info][:nickname],
:email => auth[:info][:email],
:authentications_attributes => [
Authentication.new(:provider => auth[:provider],
:uid => auth[:uid]
).attributes
])
end
end
end
代码是视频教程中@Terry老师的,我自己手动打出来的。第二行attr_accessible :email, :nickname
是生成这个 model 时自己生成的.
现在我访问http://127.0.0.1:3000/auth/github/ 或者http://127.0.0.1:3000/auth/identity/register 时,都会报这个错误:
ActiveModel::MassAssignmentSecurity::Error in SessionsController#create
Can't mass-assign protected attributes: authentications_attributes
其中 SessionsController 中的代码是这样的:
class SessionsController < ApplicationController
def create
user = User.from_auth(request.env['omniauth.auth'])
session[:user_id] = user.id
flash[:notice] = "Welcome #{user.nickname}"
redirect_to posts_path
end
def new
flash[:failure_provider] = request.env['omniauth.error.strategy'].name
flash[:failure_type] = request.env['omniauth.error.type']
end
end
.
自己尝试这样解决:
将authentications_attributes
也加在user_mode
l 的 attr_accessible :email, :nickname
中,即
attr_accessible :email, :nickname, :authentications_attributes
,这时,又报错
ActiveModel::MassAssignmentSecurity::Error in SessionsController#create
Can't mass-assign protected attributes: created_at, updated_at
发到这里,恳请各位帮忙下。谢谢~