0

这些是模型:

class Question < ActiveRecord::Base
  attr_accessible :title, :description, :inquiries_attributes

  has_many :replies

  has_many :groups, :through => :question_groups
  has_many :question_groups

  has_many :inquiries
  accepts_nested_attributes_for :inquiries, :allow_destroy=>true,
                            :reject_if=>:all_blank

  belongs_to :user
  belongs_to :last_user, :class_name => "User", :foreign_key => "last_user_id"

  acts_as_by_user

  default_scope order("created_at DESC")

  acts_as_publicable

  checkboxes_for :groups

end

class Inquiry < ActiveRecord::Base

  attr_accessible :title, :question_id, :inquiry_type_id, :inquiry_options_attributes

  belongs_to :question
  belongs_to :inquiry_type
  has_many :inquiry_options
  accepts_nested_attributes_for :inquiry_options, :allow_destroy=>true,
                            :reject_if=>:all_blank
  has_many :inquiry_replies
end

class InquiryOption < ActiveRecord::Base

  attr_accessible :content, :inquiry_id

  belongs_to :inquiry

end

这是视图:

<%= nested_form_for [:admin, @question] do |f| %>
  <%= f.error_messages %>
  <p>
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </p>
  <p>
    <%= f.label :description %><br />
    <%= f.text_area :description %>
  </p>
  <%= f.fields_for :inquiries do |inquiry_form| %>
    <p>
      <%= inquiry_form.label :title %><br />
      <%= inquiry_form.text_area :title, :size=>"40x5" %><br />
      <%= inquiry_form.label :inquiry_type %><br />
      <%= collection_select(inquiry_form, :inquiry_type_id, InquiryType.all, :id, :name, options ={:prompt => "Seleziona una tipologia"}) %><br />

      <%= inquiry_form.fields_for :inquiry_options do |inquiry_option_form| %>
      <p>
        <%= inquiry_option_form.label :content %><br />
         <%= inquiry_option_form.text_area :content, :size=>"40x5" %><br />
        <%= inquiry_option_form.link_to_remove "Rimuovi risposta" %>
      </p>
    <% end %>
    <p><%= inquiry_form.link_to_add "Aggiungi risposta", :inquiry_options %></p>

     <%= inquiry_form.link_to_remove "Rimuovi domanda" %>
    </p>
  <% end %>
  <p><%= f.link_to_add "Aggiungi domanda", :inquiries %></p>
  <p>
    <%= f.checkboxes_for :groups %>
  </p>
 <p><%= f.submit %></p>
<% end %>

在第二层,如果我想添加多个inquiry_option,只保存第一个。我看到当我添加多个查询选项时,第二个查询选项与第一个查询选项具有相同的名称属性,因此在我提交表单时只保存第一个。我该如何解决?

4

1 回答 1

2

如果您想要多个值,则需要在控制器中“构建”它们。使用您的示例,您应该将以下内容添加到newquestions_controller.rb 中的方法中

2.times do
  @question.inquiries.build
end

这将为您建立 2 个查询

于 2012-05-24T15:09:48.590 回答