【问题标题】:In Rails, although I set the model associations, how do I ensure a user can only create one instance of a resource?在 Rails 中,虽然我设置了模型关联,但如何确保用户只能创建一个资源实例?
【发布时间】: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


【解决方案1】:

您可以为 :new 和 :create 方法扩展您的 correct_user 方法: (或者创建另一个方法,然后在 before_action :new, :create 如果你希望它们分开)

before_action :correct_user, only: [:new, :create, :edit, :update]

def correct_user
  if @profile
    # edit / update
    redirect_to posts_path, notice: "Not authorized to edit this profile" if     @profile.user != current_user
  else
    # new / create
    redirect_to profile_path(current_user.profile.id) if current_user && current_user.profile
  end
end

【讨论】:

  • 非常感谢,非常聪明!
最近更新 更多