我正在努力使用simple_form
. 您将能够从下面的模型中看到一个Person
可以有很多个Phone
,所需的行为是显示任何现有数字的编辑字段加上一个额外的应为新数字,如果这个新数字不是由用户然后它只是忽略而不是保存在数据库中。我也想用Email
.
当登陆 /people/:id/edit 页面时,这个空白字段被过早地验证并在提交之前在表单上产生可见的错误。访问 /people/:id/new 页面时不会这样做;我假设这是因为new_record?
在新页面上为用户模型返回 true?在阅读类似的帖子时,我在模型上添加on: :save
了一个参数,尽管这只是允许空白记录进入数据库,也许是因为当用户模型保存记录时这不相关?validates
Phone
class Person < ActiveRecord::Base
belongs_to :company
has_many :phones, :as => :phoneable
has_many :emails, :as => :emailable
has_many :addresses, :as => :addressable
attr_accessible :first_name, :job_title, :last_name, :prefix, :phones_attributes, :emails_attributes, :addresses_attributes, :company_id
accepts_nested_attributes_for :phones, allow_destroy: true, reject_if: proc { |attributes| attributes['number'].blank? }
accepts_nested_attributes_for :emails, allow_destroy: true, reject_if: proc { |attributes| attributes['email'].blank? }
accepts_nested_attributes_for :addresses, allow_destroy: true, reject_if: :all_blank
validates :first_name, :last_name, presence: true
def to_s
"#{first_name} #{last_name}"
end
end
class Phone < ActiveRecord::Base
belongs_to :phoneable, polymorphic: true
attr_accessible :number, :phone_type
validates :number, :phone_type, presence: true, on: :save # as suggested in a similar post, just allows blank records into database.
def to_s
"#{phone_type}: #{number}"
end
end
使用 new 和 edit 控制器,我正在为这些模型中的每一个创建一个新实例,以便它们显示在表单上。作为 cancan 的一部分@person
加载到控制器中。load_and_authorize_resource
def new
@person.phones << Phone.new
@person.emails << Email.new
end
这是表单的部分视图:
<%= simple_form_for @person, :html => { :class => 'form-horizontal' } do |f| %>
<fieldset id="<%= controller.action_name.capitalize %>_person">
<legend><%= controller.action_name.capitalize %> Person</legend>
<%= f.input :prefix %>
<%= f.input :first_name %>
<%= f.input :last_name %>
<%= f.input :job_title %>
<%= f.association :company, :prompt => "Select associated company..." %>
<%= f.simple_fields_for :phones do |phone| %>
<%= phone.input :phone_type, :collection => %w(Work Home Mobile Fax Other), :default => "Work" %>
<%= phone.input :number %>
<% end %>
<%= f.simple_fields_for :emails do |email| %>
<%= email.input :email_type, :collection => %w(Work Home Other), :default => "Work" %>
<%= email.input :email %>
<% end %>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
<%= link_to t('.cancel', :default => t("helpers.links.cancel")),
people_path, :class => 'btn' %>
</div>
</fieldset>
<% end %>
非常感谢您提前提供的任何帮助:-)