Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 Active Admin add preset value to new record

I have tried to do it from the controller and from the active admin override controller and I can't make it work.

A user creates a website. current_user has an id attribute website has an user_id attribute

So when I create a new website I want to add the current_user.id into website.user_id. I can't.

Anybody know how?

Right now I need it on the new/create actions but I'll probably need this on the edit/update actions too.

like image 853
leonel Avatar asked Sep 26 '11 16:09

leonel


3 Answers

This seems to work for me:

ActiveAdmin.register Website do

  controller do
    # Do some custom stuff on GET /admin/websites/*/edit
    def edit
      super do |format|
        # Do what you want here ...
        @website.user = current_user
      end
    end
  end

end

You should be able to override other controller actions in the same way.

like image 144
malclocke Avatar answered Nov 19 '22 08:11

malclocke


ActiveAdmin.register Model do

  # also look in to before_create if hidden on form
  before_build do |record|
    record.user = current_user
  end

end

See https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/resource_dsl.rb#L156

like image 38
David Lawson Avatar answered Nov 19 '22 09:11

David Lawson


You need to add a 'new' method to the controller. The 'new' method creates an empty website object that will be passed to the form. The default 'new' method just creates an empty @website object. Your 'new' method should create the empty object, and then initialize the value of user to current user:

  ActiveAdmin.register Website do

  controller do
    # Custom new method
    def new
      @website = Website.new
      @website.user = current_user
      #set any other values you might want to initialize
    end
  end
like image 4
Chales Avatar answered Nov 19 '22 08:11

Chales