【问题标题】:Problem saving custom attribute in rails devise gem在rails devise gem中保存自定义属性的问题
【发布时间】:2020-03-08 18:32:07
【问题描述】:

我的应用程序中的身份验证系统由设计处理,现在我希望我系统中的每个用户都属于一个组织。所以每个组织都会有多个用户。 注册时,每个用户都将选择他们想要加入的组织。

当用户注册并从组合框中选择和组织时,他们会收到以下错误:

ActiveRecord::AssociationTypeMismatch in Devise::RegistrationsController#create

Organisation(#70213198483780) expected, got "1" which is an instance of String(#70213152374240)

以下是我的源代码:

app/models/organisation.rb

class Organisation < ApplicationRecord
  has_many :users
end

app/models/user.rb

class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_many :activities
  belongs_to :organisation
end

app/views/devise/registrations/new.html.erb

<h2>Sign up</h2>

<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
  <%= render "devise/shared/error_messages", resource: resource %>

  <div class="field">
    <%= f.label :email %><br />
    <%= f.email_field :email, autofocus: true, autocomplete: "email" %>
  </div>

  <div class="field">
    <%= f.label :password %>
    <% if @minimum_password_length %>
    <em>(<%= @minimum_password_length %> characters minimum)</em>
    <% end %><br />
    <%= f.password_field :password, autocomplete: "new-password" %>
  </div>

  <div class="field">
    <%= f.label :password_confirmation %><br />
    <%= f.password_field :password_confirmation, autocomplete: "new-password" %>
  </div>

  <div class="field">
    <%= f.label :organisation %><br />
    <%= f.select :organisation, Organisation.all.collect { |o| [ o.organisation_name, o.id ] }%>
  </div>


  <div class="actions">
    <%= f.submit "Sign up" %>
  </div>
<% end %>

<%= render "devise/shared/links" %>

app/controllers/application_controller.rb

class ApplicationController < ActionController::Base
  before_action :authenticate_user!
  before_action :configure_sign_up_params, if: :devise_controller?

  protected
  # If you have extra params to permit, append them to the sanitizer.
  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: [:organisation])
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby devise strong-parameters


    【解决方案1】:

    我建议您将表单更改为

    &lt;%= f.select :organisation_id, Organisation.all.collect { |o| [ o.organisation_name, o.id ] }%&gt;

    因为下拉列表将organisation.name 作为键,organisation.id 作为值。

    然后更改devise_parameter_sanitizer.permit(:sign_up, keys: [:organisation_id]) 以允许将organisation_id 分配给用户

    不要在Organisation.all 上使用collect,而是使用Organisation.all.pluck(:name, :id)。它将给出与查询相同但更优化的查询。

    【讨论】:

    • 进行这些更改后,我收到以下错误:#<0x00007ff91ff252e0>
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多