1
votes

Hi I'm working on a Rails 3.2.9 app which uses devise and ActiveAdmin. I have models like users and company. I want admin to select one manager from list of registered users for a particular company.

My user's table has these fields : id,username, email, company_id, password etc

My company's table has : id, company_name, manager_id (this is nothing but id of user), created_at etc

The following code I have written displays the users of all companies. I want only that particular company's users to be displayed in the dropdown after clicking on edit.

Here's my companies.rb file for admin

ActiveAdmin.register Company do
  index do
    column "Company", :name
    column :address
    column "No. of Subscriptions", :no_of_licenses
    column "Manager", :manager_id
    default_actions
  end
  filter :name

  form do |f|
    f.inputs "Company Details" do
      f.input :name
      f.input :address
      f.input :no_of_licenses, :label => 'No of Subscriptions'
      #THIS LINE NEEDS TO BE CHANGED
      f.input :manager_id, :as => :select, :collection => User.joins('LEFT OUTER JOIN companies ON users.company_id = companies.id').map{|u| [u.username, u.id]} 
    end
    f.buttons
  end  
end

EDIT1:

I have added a controller do and did the changes as suggested by jeremy04..Add a method in user model and call it from edit action of this controller. I'm now getting an error like

 NoMethodError in Admin::CompaniesController#edit

undefined method `[]' for nil:NilClass

Rails.root: D:/WS/som_new
Application Trace | Framework Trace | Full Trace

app/admin/companies.rb:9:in `edit'

My companies.rb file now looks like this

ActiveAdmin.register Company do

  controller do
      # This code is evaluated within the controller class

      def edit
        puts "IN EDIT"
        #@user_with_companies=[]
        @user_with_companies = User.users_with_company(params[:company][:name]).pluck(:username)
        puts @user_with_companies
      end

    end


  index do
    some code...
  end
  filter :name


  form do |f|
    f.inputs "Company Details" do
      f.input :name
      f.input :address
      f.input :no_of_licenses, :label => 'No of Subscriptions'
      f.input :manager_id, :as => :select, :collection => @user_with_companies #.map{|u| [u.username, u.id]}

    end
    f.buttons
  end 

end

1

1 Answers

0
votes

You almost got it, I would recommend doing the SQL logic in your User model (create a method that would pass in a company name) or use a scope.

def self.users_with_company(company)
  User.joins(:company).where("companies.name = ?", company)
end

Then in your edit action on your controller call your new method:

@user_with_companies = User.users_with_company(params[:company][:name])

then:

:collection => @user_with_companies.map .. .etc.