Rails: activeadmin overriding create action

Ruby on-RailsActiveadminInherited Resources

Ruby on-Rails Problem Overview


I have an activeadmin resource which has a belongs_to :user relationship.

When I create a new Instance of the model in active admin, I want to associate the currently logged in user as the user who created the instance (pretty standard stuff I'd imagine).

So... I got it working with:

controller do
  def create
    @item = Item.new(params[:item])
    @item.user = current_curator
    super
  end 
end 

However ;) I'm just wondering how this works? I just hoped that assigning the @item variable the user and then calling super would work (and it does). I also started looking through the gem but couldn't see how it was actually working.

Any pointers would be great. I'm assuming this is something that InheritedResources gives you?

Thanks!

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

I ran into a similar situation where I didn't really need to completely override the create method. I really only wanted to inject properties before save, and only on create; very similar to your example. After reading through the ActiveAdmin source, I determined that I could use before_create to do what I needed:

ActiveAdmin.register Product do
  before_create do |product|
    product.creator = current_user
  end
end

Solution 2 - Ruby on-Rails

Another option:

def create
  params[:item].merge!({ user_id: current_curator.id })
  create!
end

Solution 3 - Ruby on-Rails

You are right active admin use InheritedResources, all other tools you can see on the end of the page.

Solution 4 - Ruby on-Rails

As per the AA source code this worked for me:

controller do
  def call_before_create(offer)
  end
end

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionpatrickdaveyView Question on Stackoverflow
Solution 1 - Ruby on-RailsKarl WilburView Answer on Stackoverflow
Solution 2 - Ruby on-RailsKori John RoysView Answer on Stackoverflow
Solution 3 - Ruby on-RailszolterView Answer on Stackoverflow
Solution 4 - Ruby on-RailsjustinsAccountView Answer on Stackoverflow