我的代码是: users_controller.rb
**class UsersController < ApplicationController
def show
@user = User.find(params[:id])
end
def create
@user.create(user_params)
if @user.save
@user.fullname = @user.firstname + ‘ ‘ + @user.lastname
end
end
end**
user.rb代码:
**class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
validates :lname, presence:true, length: {maximum: 40}
validates :fname, presence:true, length: {maximum: 40}
validates :fullname, presence:true, length: {maximum: 80}
has_attached_file :avatar, styles: { medium: "300x300>", thumb: "100x100>" }, default_url: "/assets/default_image.jpeg"
validates_attachment_content_type :avatar, content_type: /\Aimage\/.*\z/
has_many :rooms
end**
并且
new.html.erb代码:
**
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= render 'shared/devise_errors' %>
<div class="form-group">
<%= f.text_field :lname, autofocus: true, class: "form-control", placeholder: "Prénom" %>
</div>
<div class="form-group">
<div class="form-group">
<%= f.text_field :fname, autofocus: true, class: "form-control", placeholder: "Nom de famille" %>
</div>
<div class="form-group">
<div class="form-group">
<%= f.text_field :fullname, autofocus: true, class: "form-control", placeholder: "Nom complet ( Prénom + Nom)" %>
</div>
<div class="form-group">**
我希望当用户填写lname和fname字段时,fullname将自动填入lname +&#39; &#39; + FNAME。
感谢您的帮助
答案 0 :(得分:1)
,只需让用户填写名字和姓氏,删除全名text_field。自动生成并在后端保存fullname。
class UsersController < ApplicationController
def create
user_params[:fullname] = "#{user_params[:firstname]} #{user_params[:lastname]}"
@user.create(user_params)
end
end