簡體   English   中英

在 rails devise gem 中保存自定義屬性的問題

[英]Problem saving custom attribute in rails devise gem

我的應用程序中的身份驗證系統由設計處理,現在我希望系統中的每個用戶都屬於一個組織。 所以每個組織都會有多個用戶。 注冊時,每個用戶將選擇他們想要加入的組織。

當用戶注冊時,他們從組合框中選擇和組織,他們收到以下錯誤:

ActiveRecord::AssociationTypeMismatch in Devise::RegistrationsController#create

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

以下是我的源代碼的樣子:

應用程序/模型/organisation.rb

class Organisation < ApplicationRecord
  has_many :users
end

應用程序/模型/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

應用程序/視圖/設計/注冊/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" %>

應用程序/控制器/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

我建議你應該改變你的形式

<%= f.select :organisation_id, Organisation.all.collect { |o| [ o.organisation_name, o.id ] }%>

因為下拉菜單將organisation.name作為鍵,將organisation.id作為值。

然后變化devise_parameter_sanitizer.permit(:sign_up, keys: [:organisation_id])以允許organisation_id要被分配給用戶

不要在Organisation.all上使用collect ,而是使用Organisation.all.pluck(:name, :id) 它將給出與更優化的查詢相同的結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM