Ruby 发表于 Rails:为什么我的嵌套表单不起作用?

Ruby on Rails: Why Isn't My Nested Form Working?

我已经跟随 RailsCast 视频创建了嵌套表单:http://railscasts.com/episodes/196-nested-model-form-part-1?autoplay=true

但由于某种原因,它没有保存。

创建电子邮件时,我试图在收件人中创建记录table,以便可以记录电子邮件发送给了哪些组和联系人。这可行,但我也在尝试将数据保存到此 table 中名为 "message" 的列,但由于某种原因,收件人 table 中的新记录已生成,但未保存邮件在 table.

我的模特是:

class Email < ActiveRecord::Base

    belongs_to :account
    has_many :recipients
    has_many :contacts, through: :recipients, :dependent => :destroy
    has_many :groups, through: :recipients, :dependent => :destroy

    accepts_nested_attributes_for :recipients
end
class Recipient < ActiveRecord::Base

   belongs_to :email
   belongs_to :contact
   belongs_to :group

end

我的 emails_controller 新方法和创建方法是:

def new
    @email = Email.new
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
end

def create
    @email = Email.new(email_params)
    if @email.save
        redirect_to @email
    else
        render 'new'
    end
end
private
def email_params
    params.require(:email).permit(:subject, :account_id, { contact_ids: [] }, { group_ids: [] }, recipient_attributes: [:message])
end

我的_form.html.erb

<%= form_for @email do |f| %>

  <% if @email.errors.any? %>
    <div id="error_explanation">
      <h2>
        <%= pluralize(@email.errors.count, "error") %> prohibited this email from being saved:
      </h2>
      <ul>
        <% @email.errors.full_messages.each do |msg| %>
          <li><%= msg %></li>
        <% end %>
      </ul>
    </div>
  <% end %>
  <p>
    <%= f.label :account_id, "Send from account" %><br>
    <% @useraccounts.each do |useraccount| %>
        <%= f.radio_button :account_id, useraccount.account_id, :checked => false %>
        <%= f.label :account_id, useraccount.account.email, :value => "true"  %><br>
    <% end %>
  </p>

  <p>
    <%= f.label :subject %><br>
    <%= f.text_field :subject %>
  </p>

  <p>
    <%= f.label :contacts, "Send to Contacts:" %><br>
    <%= f.collection_check_boxes :contact_ids, Contact.where(user_id: session[:user_id]), :id, :firstname ,{ prompt: "firstname" } %>
  </p>

 <p>
    <%= f.label :groups, "Send to Groups:" %><br>
    <%= f.collection_check_boxes :group_ids, Group.where(user_id: session[:user_id]), :id, :name ,{ prompt: "name" } %>
  </p>

   <%= f.fields_for :recipients do |t| %>
    <%= t.label :message %>
    <%= t.text_field :message %>
  <% end %>
  <p>
    <%= f.submit %>
  </p>

<% end %>

谁能帮我弄清楚为什么 message 字段没有保存在收件人 table 中,而在 table 中创建了新行?

def new
    @email = Email.new
    @email.recipients.build
    @useraccounts = Useraccount.where(user_id: session[:user_id])
end

def create
    @email = Email.new(email_params)
    @email.recipients.build(email_params[:recipient_attributes])

    if @email.save
        redirect_to @email
    else
        render 'new'
    end
end

您还需要在创建操作中创建收件人。因此,当您对@email 执行保存时,相应的收件人也会被保存。