简体   繁体   中英

Rails - Nested form - 2 levels

I want to build a form following this idea:

  • I have Assignment, Activity, Task, AssignmentActivity, ActivityTask and AssignmentActivityTask models
  • 1 assignment has many activities and 1 activity has many tasks

    • (there's a many-to-many relation between:
      • Assignment - Activity
      • AssignmentActivity - Task,
    • and a One-to-many relation:
      • Activity - Task)

I've made the Assignment-Activity form using this idea: http://railscasts.com/episodes/17-habtm-checkboxes

and the form looks like this

_form.html.erb

<% form_for @assignment do |f|%>
  <% Activity.all.each do |a|%>
    <% check_box_tag "assignment[activity_ids][]", a.id,  @assignment.activity_ids.include?(a.id)%> | <% a.name%>
  <%end%>
<%end%>

So it saves inside the assignment, all the activities that I've checked.

The problem comes when I tried to add the ability to save task inside this form. This is what I've tried

_form.html.erb

<% form_for @assignment do |f|%>
  <% Activity.all.each do |a|%>
    <%= check_box_tag "assignment[activity_ids][]", a.id,  @assignment.activity_ids.include?(a.id)%> | <% a.name%> <br>
    <% a.tasks.each do |t|%>
      #THIS
      <% check_box_tag "assignment[activity_ids][][]", t.id, "Something here"%><br>
    <%end%>
  <%end%>
<%end%>

But I'm not sure how to write the line after the comment.

So when it saves it should save inside the assignment the activities and also the tasks

Is there a way of doing this?

Thanks in advance

Javier QQ

You can try to pass the assignment id as a params and use a Helper Method to save the objects in the multiple models. In ActionView::Helpers API you have something like this:

check_box(object_name, method, options = {}, checked_value = "1", unchecked_value = "0")

So maybe try something like this in your block of code:

<% check_box_tag "assignment[activity_ids][][]", propagate(t.id)%>

And in your AssignmentHelper.rb, try to implement a method called propagate:

def propagate(id)
  *Fetch the id of Activity
  *Fetch the id of Task
  *Save both objects 
end

Hope this helps.

I'd recommend nested_forms by ryanb. It'll take care of what you're wanting to do really well and very quickly.

You don't need to use any external libraries because Rails handles nested forms just fine.

Become comfortable with using fields_for and your problems will be sorted.

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