【发布时间】:2026-02-09 12:15:01
【问题描述】:
我使用 Devise 生成了用户,并为我称为 Profiles 的资源创建了一个脚手架。我将模型设置如下:
class Profile < ActiveRecord::Base
belongs_to :user, :foreign_key => "user_id"
end
class User < ActiveRecord::Base
has_one :profile
end
我希望用户仅在创建帐户后创建配置文件,但我不希望他能够创建其他配置文件,我可以通过访问 localhost:3000/profiles/new...我怎么能做这个?另外,我将如何路由到用户的特定个人资料?我花了一整天的时间试图解决这个问题,请帮忙。
class RegistrationsController < Devise::RegistrationsController
def after_sign_up_path_for(resource)
new_profile_path
end
end
配置文件控制器
class ProfilesController < ApplicationController
before_action :set_profile, only: [:show, :edit, :update, :destroy]
before_action :correct_user, only: [:edit, :update]
before_action :authenticate_user!, only: [:index, :show, :edit, :update]
def show
end
def create
@profile = current_user.build_profile(profile_params)
if @profile.save
redirect_to @profile, notice: 'Profile was successfully created.'
else
render action: 'new'
end
end
def edit
end
def new
@profile = current_user.build_profile
end
def update
if @profile.update(profile_params)
redirect_to @profile, notice: 'Profile was successfully updated.'
else
render action: 'edit'
end
end
private
def set_profile
@profile = Profile.find(params[:id])
end
def correct_user
redirect_to posts_path, notice: "Not authorized to edit this profile" if @profile.user != current_user
end
def profile_params
params.require(:profile).permit(:pdescript)
end
end
routes.rb 文件:
devise_for :users, :controllers => {:registrations => 'registrations'}
resources :posts
resources :profiles
【问题讨论】:
-
有很多方法可以做到这一点,但基本答案是如果 Profile.find(params[:id])
标签: ruby-on-rails devise resources user-profile