Override default scope in active_admin form.has_many

For a Post model that has has_many attachments, and the attachment has a hidden flag. Throughout the application, I want to easily say post.attachments and only get visible, so I set the default scope in the Attachment model (using squeel):

default_scope -> { where { (hidden != true) | (hidden == nil) } } 

But the admin page should be able to see all attachments for the message, not just visible ones (so you can switch the hidden checkbox). By default, this method (in admin / posts.rb) uses default_scope and allows me to edit only visible ones:

 f.has_many :attachments do |a| ... end 

I know that I can simply not use default_scope and instead call it: visible, and then say post.attachments.visible everywhere (except the admin page), but I prefer not to.

How can I reset children’s investments on the admin page?

+4
source share
1 answer

Here is the solution I developed:

In the app /admin/posts.rb

 f.has_many :attachments, for: [:attachments, f.object.attachments_including_hidden] do |a| ... end 

And in app / models / posts.rb

 def attachments_including_hidden Attachment.unscoped.where( attachable_id: id ) end 

(where Attachment model belongs__ :: attachable, polymorphic: true)

What's happening? ActiveAdmin uses Formtastic, which uses the Rails Form Builder. The form.has_many method is an ActiveAdmin method that calls Formtastic form.inputs, which in turn calls the Rails_for fields. Option: for the option, fields_for will be passed completely down, which can take a collection (as its second argument), so I deliver this collection to it explicitly.

+8
source

All Articles