Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between using nested routes vs. accepts_nested_attributes_for?

I may be confusing the two entirely, but I'm seeing that forms can facilitate associations using an array argument based on nested routes, ex:

<%= form_for [@project, @task]...

or using the fields_for helper if the parent class accepts_nested_nested_attributes_for the child.

What's the difference / trade-offs between these approaches?

like image 752
Nathan Avatar asked May 04 '12 12:05

Nathan


Video Answer


2 Answers

I didn't find the answers given to be as clear as I had hoped, so after doing a bit more research I discovered an answer that satisfied me and so I figured I'd share it with others.

Nested routes approach

Basically, the nested routes approach is useful when you're presenting a form for a child model as a single form in it's own right. In other words, if you have a blog with a Post model with a Comment model as it's child, you can use nested routes to present the form for the child such that submitting that form will let rails do its magic in terms of associating the child with the parent.

Nested attributes approach

The accepts_nested_attributes_for method on the other hand, is more aptly used to present a form that while taking on the appearance of a single form, is really multiple forms merged together with a single submit button.

So to summarize, the nested routes approach deals with one model in single form (albeit associated with a parent model), while the nested attribute approach deals with multiple models in a single form.

The difference might be subtle to newcomers, but meaningful enough to understand.

Hope this helps others who had questions about this. Cheers.

like image 76
Nathan Avatar answered Oct 09 '22 11:10

Nathan


This is child model form:

<%= form_for [@project, @task] ... %>

where you submiting Task for the existent Project.

Here @project = Project.find(params[:project_id]) and @task = Task.new according to docs or @task = Task.find(params[:id]) if you're updating existing task.

This is used in the parent model form:

<%= form_for @project do |f| %>
  <%= f.fields_for :task do |builder| %>
    <% # ... %>
  <% end %>
<% end %>

where you can create or update both objects at once. Task attributes will be pass in the params[:project][:task_attributes] with task id if you're updating objects.

like image 25
jibiel Avatar answered Oct 09 '22 13:10

jibiel