gpt4 book ai didi

ruby-on-rails - 将用户 ID 链接到配置文件模型 - Ruby on Rails

转载 作者:数据小太阳 更新时间:2023-10-29 08:45:10 24 4
gpt4 key购买 nike

我有一个基本的 Rails 应用程序,其中包含设计设置和使用脚手架生成的配置文件模型。 Profile 模型是用户在注册后将在其中添加有关自己的详细信息的地方。除一个问题外,一切正常:用户创建配置文件后,新配置文件已创建,但未链接到该用户 ID。我已经生成了将 user_id 添加到配置文件的迁移。如何保存用户创建的配置文件并将其链接到当前登录的用户?

这是我当前的代码:

配置文件 Controller :

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

respond_to :html

def index
@profiles = Profile.all
respond_with(@profiles)
end

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

def new
@profile = Profile.new
respond_with(@profile)
end

def edit
end

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

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

def destroy
@profile.destroy
respond_with(@profile)
end

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

def profile_params
params.require(:profile).permit(:name, :civil, :email, :level, :employment_date, :mobile, :folder, :title, :internal, :nationality, :vacation, :work_email, :experience)
end
end

个人资料模型:

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

用户模型:

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
end

最佳答案

只要你使用devise,它应该很简单:

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

Devise 会为您创建该辅助方法。检查其 docs page .

关于ruby-on-rails - 将用户 ID 链接到配置文件模型 - Ruby on Rails,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30692011/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com