Mayerson
Mayerson

Reputation: 101

Filter by association in ruby on rails using active admin gem

I have two models: Login and Account

class Login
  belongs_to :account
  attr_accessible: first_name, primary_admin # primary_admin is boolean
end

class Account
 has_many: logins

 def primary_admin
  @primary_admin ||= self.logins.find { |l| l.primary_admin }
 end
end

So in resume an Account has many Logins, but there is only one Login with primary_admin = true. In the filters of Account I want to search for that Login (the one with primary_admin = true) but using the first_name of the Login.

Using active admin in app/admin/account.rb I have something like this

filter :primary_admin, as: :string

But is obviously not working, any help would be appreciated, thanks in advance!

Here is the database schema:

Login

id             :integer(4)      not null, primary key
email          :string(255)     default(""), not null
first_name     :string(255)
last_name      :string(255)
primary_admin  :boolean(1)
account_id     :integer(4)

Account

id              :integer(4)      not null, primary key
name            :string(255)

Upvotes: 2

Views: 8667

Answers (2)

James
James

Reputation: 774

More things you can try to find your primary_admin using filter buttons

#model/account.rb
scope :primary, where(:login_id => Login.where(:primary => true))

#admin/accounts.rb
scope :primary

or

#model/login.rb
scope :primary, where(:primary_admin => true)

#admin/logins.rb
scope :primary

Upvotes: 0

James
James

Reputation: 774

Try this if primary_admin is a string field

ActiveAdmin.register Account do
  filter :primary_admin, as: => :string
end

ActiveAdmin.register Login do
  filter :account_primary_admin, as: => :string
end

Or try this if primary_admin is a boolean field

ActiveAdmin.register Account do
  filter :primary_admin, :as => :select
end

ActiveAdmin.register Login do
  filter :account_primary_admin, :as => :select
end

and you might have to remove this

def primary_admin
  @primary_admin ||= self.logins.find { |l| l.primary_admin }
end

Upvotes: 2

Related Questions