Reputation: 2103
I have a simple situation in my database. Author
has_many Books
.
With Active Admin I want to give users the ability to add new authors with their new books.
What I have right now looks like this:
ActiveAdmin.register Author do
menu false
actions :new, :create
permit_params :books
form do |f|
f.has_many :books, new_record: true do |book|
books.inputs 'book' do
book.input :title
end
end
end
end
however, when I go to the new
action I'm getting the error
undefined method new_record? for nil:NilClass
pointing to
f.has_many :books, new_record: true do |book|
Do I need to override new
and initialize new objects? What if I want to add multiple books dynamically? Is there a default solution for such a scenario?
Upvotes: 1
Views: 640
Reputation: 1179
First you have to tell the Author
model to accept attributes of Books
. You have to do it in the model/author.rb
. Add the line -
accepts_nested_attributes_for :books, :allow_destroy => true
Then you have permit the params in active admin model the right way to accept books attributes.
books_attributes: [:title]
Then you can add the form like below where activeadmin will dynamically handle creating new object or deleting one.
f.has_many :book do |b|
b.inputs 'Books' do
b.input :title
end
end
Upvotes: 0
Reputation: 2978
Yes. If you want your form to display inputs for a blank book without the user needing to click 'Add book' (default behavior) then pre-populate a book in new:
controller do
def new
build_resource
resource.books << Book.new
new!
end
I'm not sure what you mean by "multiple books dynamically" but the default JavaScript and 'Add' button should handle that.
As commented, you do need accepts_nested_attributes_for :books
in the model and extend your permit_params.
Upvotes: 2
Reputation: 386
The first thing I could guess just from what you said is that you need to permite user params as well as books. The database needs to INSERT INTO user the same way needs INSERT INTO books. As Rails is a great framework and says "Convention over configuration", the only way we might give to you an apropriated answer is cheking your repository.
However "new_record?" method is always running when you try to INSERT INTO your database new data. You don't see it because it doesn't show nothing UNTIL you try INSERTING new datas without run another database migration.
In newest Rails version the migration is running as rails db:migrate
.
Old Rails versions use rake db:migrate
.
As I said, checking your repo is the best way to give you an appropriated answer. Cheers
Upvotes: -1