【问题标题】:Linking a user id to a profile model - Ruby on Rails将用户 ID 链接到配置文件模型 - Ruby on Rails
【发布时间】:2015-06-07 09:31:28
【问题描述】:

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

这是我当前的代码:

配置文件控制器:

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

【问题讨论】:

    标签: ruby-on-rails ruby model devise scaffolding


    【解决方案1】:

    只要你使用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

    【讨论】:

    • 我不敢相信事情就这么简单,我已经为这个问题苦苦挣扎了好几天!非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多