Home > database >  Starting with a minimum number of children in an ActiveAdmin has_many relationship
Starting with a minimum number of children in an ActiveAdmin has_many relationship

Time:07-25

Let's say I have a collection of books, each book can have multiple authors and I am using a has_many relationship between my Book and BookAuthor models.

In ActiveAdmin, I'd build the form like this:

f.has_many :book_authors, heading: 'Authors', allow_destroy: true do |ba|
  ba.input :author_type,
                  include_blank: false,
                  input_html: { autocomplete: 'off' }
  ba.input :author, input_html: { autocomplete: 'off' }
end

Is there a way for me to display a minimum number of children (say, 1) in the form by default when creating a new book?

I guess I could always emulate a click event for the add new button with JavaScript, which is a bit hacky, but I do wonder if there is a way to do this more elegantly on the Ruby/Rails side.

CodePudding user response:

Try with something like:

ActiveAdmin.register Book do
  controller do
    def build_new_resource
      super.tap do |res|
        res.assign_attributes(book_authors: [BookAuthor.new])
      end
    end
  end 
end  
  • Related