【问题标题】:Limit users to create only one profile with Devise in Rails在 Rails 中使用 Devise 限制用户只能创建一个配置文件
【发布时间】:2015-05-02 20:00:00
【问题描述】:

我有一个使用 devise 的用户模型和配置文件模型。

用户 has_one 个人资料 个人资料属于用户

如果用户在尝试创建另一个配置文件时已经与他们关联了配置文件,我该如何抛出错误。

所以如果用户访问 example.com/profiles/new 它会抛出错误

【问题讨论】:

  • 有很多方法可以做到这一点。我建议您查看 Rails 文档以了解 ActiveRecord 验证和/或挂钩(例如 before_create)

标签: ruby-on-rails ruby devise


【解决方案1】:

你可以这样做:

profiles_controller.rb

def new
  if current_user.profile.empty?
    # create profil for user
  else
    # raise error which doesn't make sense or redirect like
    redirect_to user_profile_path
  end
end

【讨论】:

  • 非常感谢。还在学习这样的东西,但它真的很有帮助!
  • @futureProgrammer25,太好了,很高兴我能帮上忙。
【解决方案2】:

@auL5agoi 回答并不会阻止某人访问创建操作。您想对这两个操作都进行检查。

def ProfilesController < ApplicationController
  before_action :check_profile_presence, only: [:new, :create]

  def new
  end

  def create
  end

  private

  def check_profile_presence
    redirect_to user_profile_path if current_user.profile.exists?
  end
end

http://guides.rubyonrails.org/action_controller_overview.html#filters

【讨论】:

    【解决方案3】:

    最好的做法是改变你的模型!这将防止您的数据库出现问题...添加到您的model/profile.rb

    class Profile < ApplicationRecord 
        belongs_to :user
        validates_uniqueness_of :user_id
    
        #[... other codes...]
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多