Awea
Awea

Reputation: 3173

ActiveAdmin customize view for has_many :through

I'm working on a ActiveAdmin app with this models :

User

class User < ActiveRecord::Base
    # A User has many roles for interact on a project
    has_many :roles, :dependent => :destroy
    has_many :projects, :through => :role
end

Role

class Role < ActiveRecord::Base
    belongs_to :user
      belongs_to :project
end

Project

class Project < ActiveRecord::Base
    # A project has many roles for interact
    has_many :roles, :dependent => :destroy
    has_many :users, :through => :role
    accepts_nested_attributes_for :roles
end

To add users with a role on each project I make this form :

form do |f|
    f.inputs "Details" do # Project's fields
        f.input :title
        f.input :code
    end

    f.has_many :roles do |app_f|
        app_f.inputs do
            if !app_f.object.nil?
                app_f.input :_destroy, :as => :boolean, :label => "Destroy?"
            end

            app_f.input :user 
            app_f.input :senior_author
        end
    end
    f.buttons
end

My first question is how can I make a with user.firstname + user.lastname. Actually I have something like this :

#<User:0x007fb98a7d6568> 

Second question is my Role model is a list of boolean attributes :

:senior_author
:first_author
:viewer
....

Can I make a with that ?

Upvotes: 0

Views: 1868

Answers (3)

Martin Poulsen
Martin Poulsen

Reputation: 442

Another solution would be to just define to_s in the model:

def to_s 
  "#{email} | #{firstname} #{lastname}" 
end

No need to set :label_method.

Upvotes: 2

Yury Alexandrov
Yury Alexandrov

Reputation: 53

Just add :label_method => lambda:

app_f.input :user, :label_method => lambda{|u| "#{u.email} | #{u.firstname} #{u.lastname}" }

Upvotes: 1

Awea
Awea

Reputation: 3173

I fix it by adding this method to models/user.rb

# format label for formtastic dropdown menu
def to_label 
  "#{email} | #{firstname} #{lastname}" 
end 

And I use it like this :

app_f.input :user, :include_blank => false, :label_method => :to_label 

Upvotes: 0

Related Questions