我有部分表单,允许用户输入将包含在出站电子邮件中的主题和消息。我想允许用户从与电子邮件所属的发票关联的联系人中选择电子邮件的收件人。通过嵌套表单选择的电子邮件收件人将存储在单独的表中。
class EmailRecipient < ActiveRecord::Base
attr_accessible :contact_id, :email_id
belongs_to :email
end
class Email < ActiveRecord::Base
attr_accessible :subject, :message, :invoice_id, :email_recipients_attributes
belongs_to :invoice
has_many :email_recipients
accepts_nested_attributes_for :email_recipients
end
<%= simple_form_for [:invoice, @email], html: {class: "form-horizontal"} do |f| %>
<%= f.error_notification %>
<% @invoice.contacts do |c|%>
<%= f.fields_for :email_recipients do |builder| %>
<%= builder.input :contact_id, :as => :check_boxes %>
<%= c.name %><br/>
<% end %>
<% end %>
<%= f.input :subject, :as => "string" %>
<%= f.input :message, :input_html => { :class => 'span7', :rows => 10 } %>
<div class="form-actions">
<%= f.button :submit, "Send Invoice", :class => 'btn-warning' %>
<%= link_to 'Cancel', invoice_path(@invoice), :class => 'btn' %>
</div>
<% end %>
答案 0 :(得分:0)
这不是最漂亮的答案,所以我很乐意看到一个更好的解决方案,但它会完成工作,直到我的技能提高。
在父表单的控制器中,我添加了:
@invoice.contacts.each { |c| @email.email_recipients.build(contact_id: c.id) }
无论是否需要,都会为所有联系人构建记录。然后在部分形式我修改了嵌套形式:
<%= simple_form_for [:invoice, @email], html: {class: "form-horizontal"} do |f| %>
<%= f.error_notification %>
<% count = 0 %>
<%= f.simple_fields_for :email_recipients do |email_recipients_form| %>
<%= email_recipients_form.input :_destroy, as: :boolean, :label => false do %>
<%= email_recipients_form.check_box :_destroy, {}, "false", "true" %>
<% contact = @invoice.contacts.find(@email.email_recipients[count].contact_id) %>
<%= contact.name + " (" + contact.email + ")" %>
<% end %>
<%= email_recipients_form.input :contact_id, as: :hidden %>
<% count += 1 %>
<% end %>