Last Updated: November 18, 2020
·
33.14K
· dpsk

Nested form and Rails 4

Rails 4 comes with the new feature called Strong Params. This is a small snipper to make it work with nested attributes.

For example you have those two models:

class Tag < ActiveRecord::Base
  belongs_to :test_set
end
class TestSet < ActiveRecord::Base
  has_many :tags
  accepts_nested_attributes_for :tags

  def tags_for_form
    collection = tags.where(test_set_id: id)
    collection.any? ? collection : tags.build
  end
end

And this form:

= simple_nested_form_for @test_set do |f|
  = f.input :name
  = f.simple_fields_for :tags, @test_set.tags_for_form do |tag|
    = tag.input :name, label: "Tag Name"
    = tag.input :test_set_id, input_html: {value: @test_set.id}, as: :hidden

Now all you need to do is permit both test_sets and tags params in the controller

def test_set_params
  params.require(:test_set).permit(:name, tags_attributes: [:id, :name])
end

That's all, you are ready to go!

11 Responses
Add your response

Beautiful...nice piece of Code
Greetings Werner

over 1 year ago ·

Beautiful.... thank you

over 1 year ago ·

Thanks! Worked for me.

over 1 year ago ·

Thanks for your explanation.
But i'm facing a problem with this concept while using 3 models instead of 2.
Where i need to include my 3rd model attributes ?
For example consider this railscasts episode
http://railscasts.com/episodes/196-nested-model-form-part-1

Here i'm able to insert survey & nested questions. But i'm not able to saving nested answers. It is not even showing any error. I have included my answers_attributes in questions controller. Please help me.

over 1 year ago ·

Amazing! Thanks a lot!

over 1 year ago ·

@srinu4122, did you ever figure out how to get the answers_attributes to save? i'm having the same problem. Any tips would be much appreciated!

over 1 year ago ·

Any suggestions on how go down another level?

over 1 year ago ·

If you can't get this to work with another doubly or more nested has many relationships, I'd check the server log. If all works but the save, most likely you have strong parameter issue. For the survey - question - answer two-level scenario, I added method to build answers collection to Question model class, but instead of the questions controller, I included answers_attributes in my survey_params private method in the survey controller, not the questions controller. I nested in the questions_attributes, like so:

params.require(:survey).permit(:title, questions_attributes: [ :id, :text, :_destroy,   answers_attributes: [ :id, :content, :_destroy ]])
over 1 year ago ·

Is there any way to define nested form on belongs_to side ?

over 1 year ago ·

good one

over 1 year ago ·

Has anybody made this method work in MySQL database using mysql2 gem? It works for me with the standard sqlite. When I nest the child element using MySQL, it does not save. I get a BEGIN and a ROLLBACK on the console and no error.

over 1 year ago ·