KingOfBabu
KingOfBabu

Reputation: 409

Ruby on Rails - Activeadmin, different validation with the same model

I did register the same Model twice with activeadmin :

ActiveAdmin.register Media, as: 'Picture' do
end
ActiveAdmin.register Media, as: 'Video' do
end

But I want to have a different validation based on the type. I want this for the video:
models/video.rb

validate :validate_video_count
def validate_video_count
    errors.add(:error, "Require minimum 1 video") if self.videos.size < 1
end

And this for the picture :
models/picture.rb

validate :validate_picture_count
def validate_picture_count
    errors.add(:error, "Require minimum 1 picture") if self.pictures.size < 1
end

Upvotes: 3

Views: 665

Answers (1)

Gabe Kopley
Gabe Kopley

Reputation: 16687

What is the reason you don't do the simpler

ActiveAdmin.register Picture do
end
ActiveAdmin.register Media do
end

This would fix your issue, I think.

If you must register the superclass, unfortunately because of a bug in the inherited_resources gem on which activeadmin depends, you need to force the instantiation of the right subclass, like this:

controller do
  def create
    klass = Picture # or Video or another subclass
    set_resource_ivar(klass.new(permitted_params["media"]))

    super
  end

  def update
    # similar pattern here to #create
  end
end

Upvotes: 1

Related Questions