Rails将表单中的一个字段映射到模型中的两个字段

时间:2015-07-13 20:08:03

标签: ruby-on-rails ruby forms

我看过很多关于如何将2个表单字段映射到一个模型字段的帖子,但是如何映射1个表单字段以提供两个(或更多)模型字段的答案呢?我有一个用户表单,它为用户提供了一个字段last_name。但我希望该用户的默认密码也是last_name(我设置了password_confirmation,因此也需要为last_name)。我该怎么做?

形式:

<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for(@user) do |f| %>

      <%= f.label :first_name %>
      <%= f.text_field :first_name, class: 'form-control' %>

      <%= f.label :last_name %>
      <%= f.text_field :last_name, :password, :password_confirmation, 
                        class: 'form-control' %>

      <%= f.label :email %>
      <%= f.email_field :email, class: 'form-control' %>

      <%= f.hidden_field :access_level, :value => "Chair" %>

      <%= f.label :Phone %>
      <%= f.text_field :phone_number, :id => "phone", class: 'form-control' %>


      <p>&nbsp;</p>
      <div class="col-md-12">
        <%= f.submit "Add Chair", class: "btn btn-primary" %>
      </div>
    <% end %>
  </div>
</div>

user_controller.rb

  def create
    @user = User.new(user_params)
    if @user.save
      log_in @user
      current_user
      flash[:success] = "Welcome to the Penn Model Congress!"
      redirect_to after_sign_in_path
    else
      render 'new'
    end
  end

  private

    def user_params
      params.require(:user).permit(:first_name, :last_name, :email, :password,
                                   :password_confirmation, :access_level, 
                                   :phone_number)
    end
end

2 个答案:

答案 0 :(得分:1)

我会在before_validation模型中添加User Greensock,如下所示:

# in app/models/user.rb
before_validation :set_default_password

private
  def set_default_password
    self.password              ||= last_name
    self.password_confirmation ||= last_name
  end

答案 1 :(得分:0)

如果这是您的默认设置,并且您不希望用户在创建时能够覆盖它,您可以在控制器上进行设置:

查看:

  <%= f.text_field :last_name, class: 'form-control' %>

控制器:

  def create
    @user = User.new(user_params)
    @user.password = @user.last_name
    @user.password_confirmation = @user.last_name
    if @user.save
       log_in @user
       current_user
       flash[:success] = "Welcome to the Penn Model Congress!"
       redirect_to after_sign_in_path
    else
      render 'new'
    end
  end