하나의 양식을 사용하여 두 모델의 데이터를 입력합니다. 부모 모델 (Tenant)을 저장할 때 User 모델에서 tenant_id의 유효성을 검사하지 않은 경우에만 하위 모델 (User)도 저장됩니다. 사용자 모델에서 validates :tenant_id, presence: true
을 수행하면 유효성 검증 오류 "사용자 임차인을 공백으로 둘 수 없음"이 표시됩니다. 어떤 아이디어?Rails 4의 관련 모델에 대해 유효성 검사가 예상대로 작동하지 않습니까?
입주 모델 :
class Tenant < ActiveRecord::Base
has_many :users, dependent: :destroy, inverse_of: :tenant
accepts_nested_attributes_for :users
before_validation do
self.status = 0
self.name = name_orig.upcase
email.downcase!
end
validates :name_orig, presence: true, length: { maximum: 255 }
validates :name, uniqueness: { case_sensitive: false }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :status, presence: true
end
사용자 모델 :
class User < ActiveRecord::Base
belongs_to :tenant, inverse_of: :users
validates_presence_of :tenant
before_validation do
self.status = 0
self.email = email.downcase
end
VALID_USERNAME_REGEX = /\A\w+\s?\w*\z/i
validates :name, presence: true, length: { maximum: 50 },
format: { with: VALID_USERNAME_REGEX },
uniqueness: { case_sensitive: false }
VALID_EMAIL_REGEX = /\A[\w+\-.][email protected][a-z\d\-]+(\.[a-z\d\-]+)*\.[a-z]+\z/i
validates :email, presence: true, length: { maximum: 255 },
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
has_secure_password
validates :password, presence: true, length: { minimum: 6 }
validates :tenant_id, presence: true
validates :status, presence: true
end
입주 컨트롤러 :
class TenantsController < ApplicationController
def new
@tenant = Tenant.new
@tenant.users.build
end
def create
@tenant = Tenant.new(tenant_params)
@tenant.save
if @tenant.save
flash[:success] = "Welcome!"
redirect_to @tenant # redirects to tenant profile
else
render 'new'
end
end
private
def tenant_params
params.require(:tenant).permit(:name_orig, :email,
users_attributes: [:name, :email, :password, :password_confirmation])
end
end
가입 양식 :
<%= form_for(@tenant) do |f| %>
<%= render 'shared/tenant_error_messages' %>
<%= f.label :name_orig, "Company name" %>
<%= f.text_field :name_orig, class: 'form-control' %>
<%= f.label :email, "Company e-mail" %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.fields_for(:users) do |u| %>
<%= u.label :name, "User name" %>
<%= u.text_field :name, class: 'form-control' %>
<%= u.label :email, "User e-mail" %>
<%= u.email_field :email, class: 'form-control' %>
<%= u.label :password, "Password" %>
<%= u.password_field :password, class: 'form-control' %>
<%= u.label :password_confirmation, "Password confirmation" %>
<%= u.password_field :password_confirmation, class: 'form-control' %>
<% end %>
<%= f.submit "Save", class: "btn btn-primary" %>
<% end %>
질문을 양식 코드로 업데이트하십시오. – Pavan
왜 두 모델의 데이터를 동시에 입력 하시겠습니까? (이미 'validates_presence_of : tenant'가 있으므로'validates : tenant_id, presence : true') –
@Pavan, 입주자 A의 첫 사용자가 가입 할 때 – Dmitri