ruby-on-railsactiveadminhas-and-belongs-to-manyvirtual-attribute

How should I access a virtual attribute from an associated model?


I have two models which are associated through has_and_belongs_to_many relationship.

I have created a virtual attribute :full_name from the first model's(User) :first_name and :last_name attributes.

I am using ActiveAdmin, and trying to show the User's :full_name attribute in it's associated model's ActiveAdmin form.

I have checked in Rails console and found that @user.full_name is in existence.

In the User model, I have defined full_name using the information I found here and here.

Below is the code from the model and from it's associated model's(Group) admin/group.rb page.

# user.rb
def full_name
  [first_name, last_name].join(' ')
end

def full_name=(name)
  split = name.split(' ', 2)
  self.first_name = split.first
  self.last_name = split.last
end

# admin/group.rb 
form do |f|     
  f.inputs 'Details' do
    f.input :description
    f.input :users, as: :check_boxes, collection: User.pluck(:full_name, :id)
    f.submit
  end
end

I am hoping to view a full name from the attributes first_name and last_name.

With my code as it is, each User that appears in the form is labeled "full_name".


Solution

  • pluck grabs column directly from the database. You are getting this error since your full_name method is not a database column.

    Change User.pluck(:full_name, :id) to

    User.select(:id, :first_name, :last_name).all.map{|u| [u.full_name, u.id] }