【问题标题】:Creating profile page for devise user RoR为设计用户 RoR 创建个人资料页面
【发布时间】:2013-11-25 12:58:52
【问题描述】:

我是 RoR 的新手,并且正在努力解决这个看似基本的项目要求。

我正在使用 Devise 进行用户身份验证,它工作正常,并且在使用 Devise 注册用户帐户后,我在注册控制器中使用自定义重定向到用户可以创建其个人资料的新页面。注册后,我不断收到以下错误:

“表单中的第一个参数不能包含 nil 或为空”。有人可以指出我正确的方向吗?提前致谢!

代码如下:

注册控制者:

class RegistrationsController < Devise::RegistrationsController
  protected

  def after_sign_up_path_for(resource)
    new_path(resource)
  end
end

创建新的个人资料页面:

<%= form_for @profile do |f| %>

<div class="field">
<%= f.label :name %>
<%= f.text_field :name %>
</div>

<div class="actions">
<%= f.submit %>
</div>

<% end %>

配置文件控制器:

class ProfileController < ApplicationController

def new
 @profiles = current_user.build_profile
end

def create
 @profiles = current_user.build_profile(params[:profile].permit( :name))
end 

end

轮廓模型:

class Profile < ActiveRecord::Base

belongs_to :user

end

用户模型:

class User < ActiveRecord::Base

devise :database_authenticatable, :registerable,
        :recoverable, :rememberable, :trackable, :validatable

validates :name, presence: true

has_one :profile

end

数据库架构文件:

ActiveRecord::Schema.define(version: 20131124211354) do

  create_table "profiles", force: true do |t|
    t.integer  "user_id"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "users", force: true do |t|
    t.string   "name"
    t.string   "location"
    t.string   "email",                  default: "", null: false
    t.string   "phone"
    t.string   "encrypted_password",     default: "", null: false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          default: 0,  null: false
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

【问题讨论】:

  • 你为什么有一个配置文件表?当您的用户表复制所有基本信息时,我不理解此架构的基本原理。无论如何,显然 profile.name 是 nil,我不知道您尝试设置它的方式/位置,但我猜它在 user_controller.rb 中,您没有显示。

标签: ruby-on-rails devise ruby-on-rails-4


【解决方案1】:

在您的 ProfileController 中,您分配 @profiles = current_user.build_profile,但在您的表单中,您引用 form_for @profile do |f|。注意复数的区别。将其更改为控制器中的@profile,您应该一切顺利...

【讨论】:

  • 我到达那里的方式是@profile,在您的情况下,它是表单中的第一个参数。为了让它为 nil 或为空,它必须没有被分配,或者查找失败,或者其他什么......
猜你喜欢
  • 1970-01-01
  • 2015-03-06
  • 1970-01-01
  • 1970-01-01
  • 2018-12-09
  • 1970-01-01
  • 2012-02-21
  • 2011-01-25
  • 1970-01-01
相关资源
最近更新 更多