Rails - 想要在使用Devise gem作为注册后为用户构建配置文件

时间:2015-07-02 14:12:49

标签: ruby-on-rails ruby devise

我正在使用Devise进行注册。但我想为用户构建一个配置文件,以便用户可以填写他们的信息。 我想为用户提供单个配置文件,但每当为该用户创建new_profile_path另一个配置文件时,我想避免用户在创建1个配置文件后转到new_profile_path或创建新的配置文件。

这是代码

User.rb

class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
     :recoverable, :rememberable, :trackable, :validatable

  has_one :profile
  has_many :statuses
end

profile.rb

class Profile < ActiveRecord::Base
 belongs_to :user
 validates_associated :user
end

profiles_controller.erb

class ProfilesController < ApplicationController
before_action :authenticate_user!
before_action :find_profile, only: [:show, :edit, :update, :destroy]

respond_to :html

  def index
    @profiles = Profile.all
  end

  def new
      @profile = Profile.new
  end

  def create
    @profile = Profile.new(profile_params)
    @profile.user_id = current_user.id
    @profile.save
    respond_with(@profile)
  end

  def show
    @profile = Profile.find(params[:id])
  end

  def edit
  end

  def update
    @profile.update(profile_params)
    respond_with(@profile)
  end


  private

    def find_profile
      @profile = Profile.find(params[:id])
    end

  def profile_params
    params.require(:profile).permit(:first_name, :last_name, :birth_date,                  
        :gender, :bio, :personal_website, :linkedin_profile,     :facebook_profile,
           :mobile_no, :telephone_no)
  end
end

这是为用户创建个人资料的当前代码。但每次通过new_profile_path为用户创建配置文件时。我怎么能避免它?

提前感谢您抽出宝贵时间。

2 个答案:

答案 0 :(得分:0)

当您使用关联时,您必须使用构建而不是新....在您的配置文件控制器...

def new 
  @profile = current_user.build_profile
end

def create
  @profile = current_user.build_profile(profile_params)
  if @profile.save
    flash[:success] = "Profile saved"
    redirect_to current_user_path
  else
    flash[:error] = "Error"
    render: new
  end
end

这将确保只为每个用户创建一个配置文件...

def edit
  @profile = current_user.profile.find(params[:id])
end

def update
  @profile = current_user.profile.find(params[:id])
  if @profile.update_attributes(profile_params)
    flash[:success] = "Successfully updated"    # Optional
    redirect_to user_path
  else
    flash[:error] = "Error"       # Optional
    render :edit
  end
end

答案 1 :(得分:0)

一种解决方案是:

# in User model

has_one :profile
before_create :init_profile

private

def init_profile
  build_profile
end

或者您可以简化操作:

# in User model

has_one :profile
after_create :create_profile
相关问题