pinzonjulian
pinzonjulian

Reputation: 181

Rails: Split fields_for for same instance in a has_many relationship

In order to have a coherent experience, I need to create a form which splits fields for an associated model. For a has_one association it works perfectly, however for a has_many, things go south.

class Book < ApplicationRecord
  has_many :pages
  acceptes_nested_attributes_for :pages
end

--

class Page < ApplicationRecord
  belongs_to :book
end

--

class BooksController < ApplicationController
  def new
    @book = Book.new
    @page = @book.pages.build
  end
end

--

new.html.slim

= form_for @book do |f|
  # normal book fields

  = fields_for :pages, @page do |p|
    p.text_field :title
    p.number_field :title_size

  # some more book fields

  HERE'S THE CATCH. I need to add some more fields for THE SAME PAGE

  = fields_for :pages, @page do |p|
    p.text_area :body
    p.number_field :page_number

The thing is, when I send the form, in my strong params I get as many indices as fields_for I write.

ActionController::Parameters{... "pages_attributes" => "0" => {"title"=> "","title_size"=> ""}, "1" => { "body"=> "", "page_number"=> "" } }

0 and 1 in Actioncontroller::Parameters correspond to each fields_for I place, even though I am specifically using the record_object attribute with @page. I need all of those fields_for to correspond to the same instance.

What am I doing wrong? I'm out of options now. Thanks in advance!

Upvotes: 2

Views: 245

Answers (0)

Related Questions