简体   繁体   中英

In Rails, how do I create a link to a new child element when the parent element doesn't exist yet?

I'm building a form to create an exam object that starts with 1 question, and I want to have a button for "New Question" that will AJAX in another question field.

The form works great with only the single question, my problem comes in when I'm trying to create the link to AJAX in another question field. If I use something like:

<%= link_to "New Question", new_exam_question_path(@exam), :remote => true %>

rails throws a no route matches error because @exam doesn't actually exist yet. If I replace @exam with Exam.find(10) it will work properly to generate a link for exam 10.

Ideally I'd like to be able to AJAX in as many questions as required. My single question is being created like below, am I able to re-use that code for the AJAX call:

<%= form.fields_for :questions do |f| %>
  <div class="edit_questions">
      <div class="exam_question">
        <%= f.hidden_field :question_type %>
        <%= f.label "Question" %><br/>
        <%= f.text_field :copy %>
          <div>
            <% if !f.object.id.blank? %>
              <%= link_to "Delete", exam_question_path(@exam, f.object), :method=>:delete, :class => "button" %>
            <% end %>
          </div>
      </div>
  </div>
<% end %>

Solved: rails casts 196 and 197 give you all the background required to solve my problem.

this is definitely not the simplest of fixes, but these rails casts were very similar to what I'm trying to do so I could follow very closely. Following the naming conventions shown in the cast is important as there are dynamically built during the process and it will break if you don't follow the naming conventions.

为什么不只在渲染视图之前实例化控制器中的空检查对象?

@exam = Exam.new

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM