rolify+activeAdmin add role by form

1.2k views Asked by At

i m using rolify+activeadmin gems. I have 2 resource: Staff and User (default devise table). Staff is a model that map an only read table, so i can't write in staffs table. i'm trying with active admin to add a role for a user using has_one and belongs_to associations:

class User < ActiveRecord::Base
  rolify
  belongs_to :staff
end

class Staff < ActiveRecord::Base
  has_one :user
end

in the app/admin/staff.rb class i have this:

    form do |f|
      f.inputs "Add role" do  |staff|
        f.input :roles,  :as => :select,      :collection => Role.global
      end
      f.actions
    end

So i want to add a role for a user using Staff admin resource.
when i click on submit form button i have this error:
NoMethodError in Admin/staffs#edit

Showing app/views/active_admin/resource/edit.html.arb where line #1 raised:

undefined method `roles' for #<Staff:0x00000005c6af70>
Extracted source (around line #1):

1: insert_tag renderer_for(:edit)
1

There are 1 answers

0
scarver2 On BEST ANSWER

Roles is part of User model, not Staff model. Add your form to app/admin/user.rb instead, and then you will be able to assign a role to a user. Also, in the user's form, you can assign the staff record. Here is an example form:

# app/admin/user.rb
form do |f|
  f.inputs 'Name' do
    f.input :name
  end

  f.inputs 'Add role'
    f.input :roles,  :as => :select, :collection => Role.global
  end

  f.inputs 'Staff' do
    f.input :staff
  end

  f.actions
end  

You can also add a delegate to staff to be able to read the roles natively in the Staff model.

# app/models/staff.rb
class Staff < ActiveRecord::Base
  attr_accessible :name, :user_id
  has_one :user
  delegate :roles, :to => :user
end