Cocoon第一个选项不保存 - 嵌套字段

时间:2016-03-21 12:17:29

标签: ruby-on-rails simple-form cocoon-gem

我正在使用Cocoon作为嵌套表单,但是第一组字段不保存到数据库中,如果我创建第二行它们似乎保存得很好?

我猜它只是我忽视的东西

.*?
class Form < ActiveRecord::Base
    has_many :questions
    accepts_nested_attributes_for :questions, :reject_if => :all_blank, :allow_destroy => true
end

----- form_controller.rb

class Question < ActiveRecord::Base
    belongs_to :form
end
def new
  @form = Form.new
  @form.questions.build
end 

def create
  @form = Form.new(form_params)

  if @form.save
     redirect_to action: "show", id: @form.id
  else
     render('new')
  end
end

def form_params
 params.require(:form).permit(:title, :description, :status, questions_attributes: [:form_id, :question_type, :question_text, :position,   :answer_options, :validation_rules, :done, :_destroy])
end

---- _question_fields.html.erb

<%= simple_form_for Form.new ,:url => {:action => :create} do |f| %>
    <div class="section-row"> 
      <div class="section-cell">
        <%= f.label :title, "Form Title" %>
        <%= f.text_field :title, placeholder: "Form Title" %>
        <br/></br>
        <%= f.label :description, "Form Description" %>
        <%= f.text_area :description, placeholder: "Form Description" %>
        <%= f.hidden_field :status, value: "online" %>
      </div>
    </div>
    <div class="section-row"> 
      <div class="section-cell">
        <div id="questions">
          <%= simple_fields_for :questions do |question| %>
            <%= render 'question_fields', :f => question %>
            <%= link_to_add_association 'add question', f, :questions %>
          <% end %>
        </div>
      </div>
    </div>
    <div class="section-row"> 
      <div class="section-cell">
        <%= f.submit "Create Ticket", class: "btn btn-primary btn-lg" %>
      </div>
    </div>
  <% end %>

2 个答案:

答案 0 :(得分:0)

您在simple_fields_for中写了x = Struct.new(:att) p x --output:-- #<Class:0x007f8c3126c568> 你应该按照以下方式编写表格(如文件所示):

link_to_add_association

答案 1 :(得分:0)

您忘记了f前面的simple_fields_forsimple_fields_for不知道表单和关联,因此它会将发布到控制器的参数命名为不同的,因此它将被强大的参数定义阻止。

所以,如果你写

f.simple_fields_for :questions do |question|

它应该正常工作;)

较小的评论:

  • link_to_add_association应该在循环之外,否则在没有循环的情况下它将不可见,并且将针对每个问题显示(在您的UI中可能有意义或可能没有意义)。
  • 您应该在id的强参数中添加questions_attributes(对编辑/删除很重要)