Rails和devise:模型属性不被持久化 [英] Rails and devise: model attribute not being persisted

查看:156
本文介绍了Rails和devise:模型属性不被持久化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编辑devise的 RegistrationsController :: create 方法稍微修改行为。我想要做的是,如果数据库中没有管理员用户,首先注册的用户将被分配给管理员角色,否则它将是普通用户。

I edited devise's RegistrationsController::create method to modify slightly the behaviour. What I'm trying to do is that if there are no admin users in the database, the one that first signs up is going to be assigned the admin role, else it will be a regular user.

但是,尽管角色虽然被正确地分配给对象(测试),但并没有被持久化到数据库中。

However, the role, though assigned correctly to the object (tested), it's not being persisted to the database.

模型:

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  attr_accessor :role

  Roles = [ :admin, :default ]

  def is? requested_role
    self.role == requested_role.to_s
  end

  def self.admin_role
    return Roles[0]
  end

  def self.default_role
    return Roles[1]
  end
end

修改的设计方法:

def create
  build_resource(sign_up_params)

  admin_user = User.find_by_role(User.admin_role)
  if admin_user.nil?
    resource.role = User.admin_role
  else
    resource.role = User.default_role
  end

  # here puts resource.role shows what's expected is indeed being assigned to the object

  if resource.save
    ...
  end
end

为什么角色存储在数据库中?为什么它 NULL

Why isn't the role being stored in the database? Why is it NULL?

推荐答案

您不需要 attr_accessor for :role 如果您将其定义为表上的一列。 ActiveRecord 只需在相关表格中定义相关列,即可为数据库备份访问器

You don't need the attr_accessor for :role if you have this defined as a column on your table. ActiveRecord gives you the database backed accessors just by having the relevant column defined in the relevant table.

您的 attr_accessor 将覆盖这些,并阻止他们将更改保留到数据库。

Your attr_accessor will be overriding these and preventing them from persisting your changes to the database.

这篇关于Rails和devise:模型属性不被持久化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆