66

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!

patrickdavey
  • 1,966
  • 2
  • 18
  • 25

4 Answers4

131

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
Karl Wilbur
  • 5,898
  • 3
  • 44
  • 54
16

Another option:

def create
  params[:item].merge!({ user_id: current_curator.id })
  create!
end
Kori John Roys
  • 2,621
  • 1
  • 19
  • 27
2

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

zolter
  • 7,070
  • 3
  • 37
  • 51
  • 2
    Damn, upon re-reading the docs properly (apologies for anyone else reading this)... I should have just called create! instead of super above. Though I think it'll do the same thing. – patrickdavey Dec 03 '12 at 04:23
-2

As per the AA source code this worked for me:

controller do
  def call_before_create(offer)
  end
end
justinsAccount
  • 742
  • 1
  • 10
  • 10
  • You pulled this from the tests. It is only there as a mockup. This only works if you create add a `call_before_create` method in your registered resource. Here you can see where they make the `call_before_create` method as a muckup for testing: https://github.com/activeadmin/activeadmin/blob/d25e8d09f723fc3ae55a21cd22bc7c6466ba32f8/spec/unit/resource_controller_spec.rb#L58-L79 – Karl Wilbur Apr 05 '21 at 13:08