16

I am making my own custom view that I need to make the process of creating associated models less painful for my users. I want to display all of the models associated pieces in-line, with controls to edit them. This is quite easy to roll my own for the basic fields, but I'd rather use a form_filtering_select partial for the inline model's associations, but I can't find any documentation to do this.

Awais
  • 1,803
  • 22
  • 26
Daniel
  • 1,188
  • 11
  • 22

2 Answers2

1

You can use Nested Form

Consider a User class which returns an array of Project instances from the projects reader method and responds to the projects_attributes= writer method:

class User
  def projects
    [@project1, @project2]
  end

  def projects_attributes=(attributes)
    # Process the attributes hash
  end
end

Note that the projects_attributes= writer method is in fact required for fields_for to correctly identify :projects as a collection, and the correct indices to be set in the form markup.

When projects is already an association on User you can use accepts_nested_attributes_for to define the writer method for you:

class User < ActiveRecord::Base
  has_many :projects
  accepts_nested_attributes_for :projects
end

This model can now be used with a nested fields_for. The block given to the nested fields_for call will be repeated for each instance in the collection:

<%= nested_form_for @user do |user_form| %>
  ...
  <%= user_form.fields_for :projects do |project_fields| %>
    <% if project_fields.object.active? %>
      Name: <%= project_fields.text_field :name %>
    <% end %>
  <% end %>
  ...
<% end %>

Here goes the Reference for details.

Malik Shahzad
  • 6,703
  • 3
  • 37
  • 49
Awais
  • 1,803
  • 22
  • 26
  • Do you have an example of what I would write to process the attributes hash in this example? – alex Jan 09 '18 at 22:21
0

There's a cool gem out there that does pretty much what you want. It's called Nested Form Fields. It allows you to edit records (along with their has_many associations) on a single page. The cool thing about it is that it even uses jQuery to dynamically add/remove form fields without a page reload. Checkout out the gems docs for proper usage. Hope that helps!

Danny López
  • 126
  • 5