【问题标题】:Devise, create a user that belongs to company设计,创建一个属于公司的用户
【发布时间】:2018-06-29 15:42:49
【问题描述】:

我想用 Devise 创建一个具有 belongs_to 关联的用户。

缺少什么?从选择列表中创建属于公司的用户需要什么?

我的表格有这个:

.siimple-form-field
        = f.label :name, class: "siimple-label"
        br
        = f.text_field :name, autofocus: true, autocomplete: "email", class: "siimple-input siimple-input--fluid siimple--height-50"
      .siimple-form-field
        label.siimple-label
          | Select an option:
        = f.fields_for :company_attributes do |b|
          = b.select :company, Company.all.collect{|p| [p.name, p]}, {}, class: "siimple-select siimple-select--fluid"

表单显示正常,所以当我尝试提交时,它说:

1 error prohibited this user from being saved:

    Company must exist

我的 RegistrationsController 也有:

def create
  super
end


def configure_sign_up_params
  devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :bank])
end

【问题讨论】:

  • 我对 HAML 并不容易,但您使用 fields_for 这是获取属于另一个模型的字段的一种方式。我不确定您是否可以(轻松地)使用 Devise 做到这一点。您应该查询的唯一字段是您的设计模型的字段。如果您的设计模型用户是公司的孩子,只需询问 company_id 字段,该字段无论如何都应该是您的用户设计模型字段之一。 (您可以通过使用选择助手显示公司名称来使其更好)
  • (我认为您要添加用户的公司已经存在。如果您想创建公司和用户一起创建,这是另一回事)
  • 公司已经存在,我有一个选择列表,用于选择必须属于的公司。

标签: ruby-on-rails devise slim-lang


【解决方案1】:

解决了!

首先,注册控制器没有在路由文件中覆盖,只是得到了这个:

devise_for :users, controllers: {
    sessions: 'users/sessions',
    # something missing no?

  }

已修复

devise_for :users, controllers: {
    sessions: 'users/sessions',
    registrations: 'users/registrations'

  }

然后,只需做一些常见的事情,比如将这样的东西添加到 控制器

def create
  params[:user][:company] = Company.find(params[:user][:company_id])
  super
end

并将缺少的权限添加到 configure_sign_up_params

def configure_sign_up_params
  devise_parameter_sanitizer.permit(:sign_up, keys: [:name, :company_id, :company])
end

【讨论】:

    【解决方案2】:

    我认为您的问题是不允许使用公司参数(这意味着公司被设置为nil,因此出现Company must exist 错误)。

    您必须覆盖 Devise 的 resource_params 方法才能添加您的 company_id 属性。尝试将其放入您的注册控制器中:

     def resource_params
        params.require(:user).permit(:user_attribute_foo, :user_attribute_bar, :company_id)
     end
    

    【讨论】:

      【解决方案3】:

      我认为您的列名称是 company_id 并且您在表单中使用的是公司。尝试更改它并允许此参数。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-11-20
        • 1970-01-01
        • 2012-03-11
        • 1970-01-01
        • 1970-01-01
        • 2019-09-30
        • 2017-04-30
        • 1970-01-01
        相关资源
        最近更新 更多