我的org_person.rb模型中有以下内容
class OrgPerson < ActiveRecord::Base
has_and_belongs_to_many :TypRole
has_and_belongs_to_many :OrgContact
has_one :OrgCredential, dependent: :destroy
belongs_to :OrgCompany, foreign_key:"org_company_id"
belongs_to :TypPosition, foreign_key:"typ_position_id"
validates :first_name, presence: true
validates :last_name, presence: true
accepts_nested_attributes_for :OrgCredential
end
class OrgCredential < ActiveRecord::Base
belongs_to :OrgPerson, foreign_key:"org_person_id"
validates :user_name, presence: true
validates :password, length: { minimum: 6 }
before_create :create_remember_token
has_secure_password
end
并在我的 org_person_controller.rb
中 def new
@person = OrgPerson.new
end
并在我的 new.html.erb
中 <%= form_for(@person) do |f| %>
<%= render 'shared/error_messages' %>
<div class="col-md-12 ">
<%= f.text_field :first_name, placeholder: "First Name", :class => "form-control" %>
<%= f.text_field :last_name, placeholder: "Last Name", :class => "form-control" %>
<%= f.fields_for :org_credentials do |oc|%>
<%= oc.password_field :password, placeholder: "Password", :class => "form-control" %>
<%= oc.password_field :password_confirmation, placeholder: "Password Confirmation", :class => "form-control" %>
<% end %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
</div>
<% end %>
在 shared / error_messages
中 <% if @person.errors.any? %>
<div id="error_explanation" class="col-md-12">
<div class="alert alert-danger" role="alert">
The form contains <%= pluralize(@person.errors.count, "error") %>.
</div>
<ul>
<% @person.errors.full_messages.each do |msg| %>
<li>* <%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
问题是必须填写所有字段才能通过。但是,当我提交一个空表单时,我只会收到错误“名字不能为空”和“姓氏不能为空”。密码验证未显示。如果有人有任何见解,请发表评论。这让我疯了。
答案 0 :(得分:1)
Models
中的许多错误都可能导致您遇到的问题。
您的Models
设置应如下所示
class OrgPerson < ActiveRecord::Base
has_and_belongs_to_many :typ_roles
has_and_belongs_to_many :org_contacts
has_one :org_credential, dependent: :destroy
belongs_to :org_company, foreign_key:"org_company_id"
belongs_to :typ_position, foreign_key:"typ_position_id"
validates :first_name, presence: true
validates :last_name, presence: true
accepts_nested_attributes_for: org_credential #this is much important
end
class OrgCredential < ActiveRecord::Base
belongs_to :org_person, foreign_key:"org_person_id"
validates :user_name, presence: true
validates :password, length: { minimum: 6 }
before_create :create_remember_token
has_secure_password
end
与has_one org_credential
有org_person
关系,因此new.html.erb
<%= f.fields_for :org_credentials do |oc|%>
应该是
<%= f.fields_for :org_credential do |oc|%>
您应该查看这些 Guides ,以便正确设置model associations
。