我是Rails的新手,並且正在建立一個工作板marketplace.I'm卡住了用戶註冊配置文件表單。我在Rails 5中使用了devise(4.2)。我在user_create之前創建了配置文件,然後只是重定向到配置文件視圖,現在使用註冊表單字段(如first_name & last_name)更新用戶。Rails 5 - 在設計sign_up後清空用戶配置文件
我的註冊是一個雙向過程,而不是嵌套的配置文件。 第1步 - 設計註冊表格,只需要一個額外的字段來檢查用戶作爲用戶(求職者)或公司的角色。 第2步 - 基於此角色,爲用戶和公司創建單獨的配置文件表單。如果配置文件未提交給數據庫,則用戶也不應保存,並且必須再次發生用戶sign_up。
目前,我只用一個通用的用戶表單,它具有first_name和last_name字段。我在用戶模型中使用了before_create:build_profile,但它只是傳遞Profile.create而不在數據庫上創建它。我應該在profiles_controller還是registrations_controller(設計)中覆蓋'create'或'new'。
views/profiles/show.html.erb中的錯誤是:表單中的第一個參數不能包含零或爲空。在終端上,我看到這個配置文件:「user_id」=>「2」,「id」=>「profile_id」} ...這是否表示DB中的用戶和配置文件表之間的東西阻礙了創建或路由正確設置?
的routes.rb
Rails.application.routes.draw do
root "jobs#index"
devise_for :users, :controllers => {registrations: "registrations"}
resources :users do
resources :profiles, only: [:show, :update]
end
end
Registrations_controller
class RegistrationsController < Devise::RegistrationsController
protected
def after_sign_up_path_for(user)
if resource.class == User && current_user.role == 'user'
user_profile_path
else # to check for company user resource.class == User && current_user.role == 'company'
puts "redirecting to company profile-will do later"
end
end
end
profiles_controller.rb
class ProfilesController < ApplicationController
def show
end
def update
@profile = Profile.find_by_user_id(profile_params)
current_user.update(@profile)
end
def destroy
@profile.destroy
respond_with(@profile)
end
private
def profile_params
params.require(:user).permit(profile_attributes: [])
end
def set_profile
@profile = Profile.find(params[:id])
end
end
profile.rb
class Profile < ApplicationRecord
belongs_to :user
end
user.rb
class User < ApplicationRecord
before_create :build_profile
devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
enum role: [:user, :company, :admin]
has_one :profile
def build_profile
Profile.create
true
end
感謝但實際上延伸到配置文件和用戶公司是下一個過程現在配置文件沒有被創建。 – Means