【问题标题】:show user's first_name with devise用设计显示用户的名字
【发布时间】:2018-01-05 09:31:33
【问题描述】:

如何在页面中显示用户的名字,例如“你好,current_user.first_name”,我的架构

create_table "users", force: :cascade do |t|
    t.string "email", default: "", null: false
    t.string "encrypted_password", default: "", null: false
    t.string "first_name", default: "", null: false
    t.string "last_name", 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", null: false
    t.datetime "updated_at", null: false
    t.index ["email"], name: "index_users_on_email", unique: true
    t.index ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true
  end

当我尝试在我的页面 <span>Hello, <%= current_user.email %></span> 中进行操作时,一切正常,但是当我尝试 <span>Hello, <%= current_user.first_name %></span> 时,它什么也没显示。我的错在哪里?

【问题讨论】:

  • 请分享您存储的当前用户的基本信息。
  • @asda111sd 如果你知道current_userid 然后检查rails 控制台User.find(1).first_name.present? 这里我给了1 用户ID 你可以通过current_user id 检查它
  • current_user.id 工作正常
  • @asda111sd 你说的是同样的事情,但最终也不起作用。请更正。
  • @asda111sd 不,你没有明白我的意思,我的意思是在 Rails 控制台上检查 User.find(current_user_id).first_name.present?如果它返回真假?并将 current_user_id 替换为您的 current_user.id

标签: ruby-on-rails model-view-controller devise


【解决方案1】:

这里的问题出在你的架构中,如果你没有传递 first_name,你有 t.string "first_name", default: "", null: false 它将空字符串保存在你的数据库中。我很确定你无论如何都没有将 first_name 值保存给用户并且它默认设置为“”。当您尝试在此处访问<span> <%= "Hello, #{current_user.first_name}" %></span> 时,它返回空字符串。此处用户存在,就好像用户不存在一样,那么它会给出first_name for nil:NilClass 的错误。

将此添加到您的应用程序控制器

    before_action :configure_permitted_parameters, if: :devise_controller?

  protected

  def configure_permitted_parameters
    permit_attrs(%i[first_name last_name])
  end

  def permit_attrs(attrs)
    %i[sign_up account_update].each do |action|
      devise_parameter_sanitizer.permit(action, keys: attrs)
    end
  end

在您的 new.html.erb 中,您有两个名字字段更改如下:

  <div class="field">
    <%= f.label :first_name %><br />
    <%= f.text_field :first_name, autofocus: false, class: "form-control" %>
  </div>

  <div class="field">
    <%= f.label :last_name %><br />
    <%= f.text_field :last_name, autofocus: false, class: "form-control" %>
  </div>

【讨论】:

  • 好的,我更改了默认值,但它仍然不保存字段(
  • 是否有任何错误?还提供传递的参数
  • 请在创建动作中发送参数
  • 我没有任何用户控制器,因为 Rails 没有生成它
  • 如果有帮助,我可以给 github 的链接
猜你喜欢
  • 2015-01-17
  • 1970-01-01
  • 1970-01-01
  • 2015-05-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多