然后使用虚拟属性验证以创建设计用户

时间:2017-06-16 13:19:35

标签: html ruby-on-rails devise

所以我有两个模型,User和Employee。用户有一名员工,员工属于用户。我想创建一个员工,但首先我必须创建一个新用户。我的Employee模型没有属性:email, :password, :password_confirmation所以我创建了虚拟属性。这是弹出Validation failed: Email is invalid, Password confirmation doesn't match Password

的错误

这是我的员工模型

class Employee < ApplicationRecord
belongs_to :user

attr_accessor :email, :password, :password_confirmation
validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :password, confirmation: true
end

我的员工控制员

class EmployeesController < ApplicationController
  def create
    @newuser=User.create!(
      email: :email,
      password: :password,
      password_confirmation: :password_confirmation
    )

    @employee = Employee.new(employee_params)
    respond_to do |format|
      if @employee.save
        format.html { redirect_to @employee, notice: 'Employee was successfully created.' }
        format.json { render :show, status: :created, location: @employee }
      else
        format.html { render :new }
        format.json { render json: @employee.errors, status: :unprocessable_entity }
      end
    end
  end

private
  def employee_params
    params.require(:employee).permit(:name, :contact_no, :role_id, @newuser.id)
  end
end

我的表格

&#13;
&#13;
<%= form_for(employee) do |f| %>
  <% if employee.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(employee.errors.count, "error") %> prohibited this employee from being saved:</h2>

      <ul>
      <% employee.errors.full_messages.each do |message| %>
        <li><%= message %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  
  <div class="field">
    <%= f.label :email %>
    <%= f.email_field :email %>
  </div>
  
  <div class="field">
    <%= f.password_field :password %>
    <%= f.password_field :password_confirmation %>
  </div>
  
  <div class="field">
    <%= f.label :name %>
    <%= f.text_field :name %>
  </div>

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

  <div class="field">
    <%= f.label :role_id %>
    <%= f.number_field :role_id %>
  </div>

  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>
&#13;
&#13;
&#13;

我还在学习rails并非常感谢你的帮助

2 个答案:

答案 0 :(得分:0)

如果您没有属性:email,:password,:password_confirmation,则删除以下验证:

validates :email, format: { with: /\A([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})\z/i, on: :create }
validates :password, confirmation: true

来自员工模型。

答案 1 :(得分:0)

我找到了我的问题的解决方案,似乎我的用户参数没有遵循rails的强参数规则。所以我的控制器现在有了这个

def employee_params
  params.require(:employee).permit(:name, :contact_no, :role_id)
end

def user_params
  params.require(:employee).permit(:email, :password, :password_confirmation)      
end

然后我能够让用户使用参数而没有问题。