如何在页面中显示用户的first_name,如" Hello,current_user.first_name",my schema
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>
它没有显示任何内容。我的错误在哪里?
答案 0 :(得分:0)
问题出现在你的架构中,你有t.string "first_name", default: "", null: false
将空字符串保存在你的数据库中,如果你没有通过first_name.I&#39;我很确定你没有保存无论如何,first_name值对用户而言默认设置为&#34;&#34;。当您尝试在此处访问<span> <%= "Hello, #{current_user.first_name}" %></span>
时,它将返回空字符串。如果用户不在,则存在用户,那么它将给出错误first_name for nil:NilClass
。
将此添加到您的ApplicationController
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>