簡體   English   中英

Rails - 如何使用設備和多態關聯在單選按鈕上進行配置文件切換?

[英]Rails - how can I make a profile switch on a radio button using a device and polymorphic associations?

我是 Rails 開發的新手。 我需要有關自定義設備的幫助。 我有具有多態關聯的用戶 - 可分析的。 注冊時,我需要根據選擇的單選按鈕填寫概要文件。

class Users::RegistrationsController < Devise::RegistrationsController
  before_action :configure_sign_up_params, only: [:create]
  before_action :configure_account_update_params, only: [:update]

  protected

  def configure_sign_up_params
    devise_parameter_sanitizer.permit(:sign_up, keys: %i[email profilable])
  end

  def configure_account_update_params
    devise_parameter_sanitizer.permit(:account_update, keys: %i[email])
  end
end

model 用戶

class User < ApplicationRecord
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  belongs_to :profilable, polymorphic: true

  def set_client_profile
    c = ClientProfile.new
    self.profilable = c
  end

  def set_realtor_profile
    r = RealtorProfile.new
    self.profilable = r
  end
end

model 客戶資料

class ClientProfile < ApplicationRecord
  has_one :user, as: :profilable
end

model RealtorProfile

class RealtorProfile < ApplicationRecord
  has_one :user, as: :profilable
end

這在我看來/設計/注冊/new.html.erb

<div class="field">
    <%= f.label :profilable, 'Client' %>
    <%= f.radio_button :profilable, 'Client' %>
    <%= f.label :profilable, 'Realtor' %>
    <%= f.radio_button :profilable, 'Realtor'%>
    <% if params[:profilable] == 'Client' %>
      <% resource.set_client_profile %>
    <% else %> 
      <% resource.set_realtor_profile %>
    <% end %>
  </div>

這是注冊后的錯誤:

1 個錯誤禁止保存此用戶: Profilable 必須存在

對不起這個可怕的代碼

這部分代碼

 <% if params[:profilable] == 'Client' %>
      <% resource.set_client_profile %>
    <% else %> 
      <% resource.set_realtor_profile %>
    <% end %>

只會在視圖渲染時執行。 此處的resource是一個空的 model,您僅用於創建表單。 此實例不是實際的 model,它將在create請求到達服務器后創建。 因此, set_client_profileset_client_profile都不會在 controller 的create方法中被調用。 應刪除此代碼。

我想最簡單的方法是在Users::RegistrationsController中重新定義create方法。 該方法的原始代碼可以在repo中找到。 所以,可以這樣修改:

 def create
    build_resource(sign_up_params)

    #here comes your modification
    if sign_up_params[:profilable] == 'Client'
      resource.set_client_profile
    else
      resource.set_realtor_profile
    end

    resource.save
    # After that, copy the rest of the original `create` method
    ...

暫無
暫無

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

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