samedi 11 juillet 2015

rails_admin when editing a belongs_to association display user name instead of User id

I have a Rails 3.2.21 app using Rails Admin.

I've written an initializer on a specific model ClockEvent for all of my actions. In particular in the list/show/edit actions I want to display actual user's full name instead of the User #1.

From the code below, I have list and show working with pretty_value, but I'm stumped when it comes to my edit action how to get the dropdown/search fields to display the User full_name (which is a field in User.rb) instead of User #1.

Here's my code below.

user.rb

has_many :clock_events

clock_event.rb

belongs_to :user

config/initializers/rails_admin.rb

RailsAdmin.config do |config|
  config.authorize_with do |controller|
    unless current_user.role == 'admin'
      redirect_to main_app.root_path
      flash[:error] = "You are not an admin"
    end
  end

  config.model 'ClockEvent' do
  configure :user, :belongs_to_association
  configure :station, :belongs_to_association
    list do
      field :clock_in
      field :clock_out
      field :user do
        pretty_value do
            value.try(:full_name)
        end
      end
      field :station do
        pretty_value do
            value.try(:station_name)
        end
      end
      field :created_at
      field :updated_at
    end

    show do
      field :clock_in
      field :clock_out
      field :user do
        pretty_value do
            value.try(:full_name)
        end
      end
      field :station do
        pretty_value do
            value.try(:station_name)
        end
      end
      field :comment
      field :hr_comment
      field :created_at
      field :updated_at
    end

    edit do
      field :clock_in
      field :clock_out
      field :user do
        pretty_value do
            value.try(:user).try(:full_name)
        end
      end
      field :station do
        pretty_value do
            value.try(:station_name)
        end
      end
      field :comment
      field :hr_comment
      field :created_at
      field :updated_at
    end
    export do; end
    create do; end
    update do; end
 end
end

As you can see, I'm also doing this for another belongs_to model for station, but I'm focusing on the user model and how to get the edit fields to search by username or fullname instead of displaying User #1 which is pretty worthless.

If you have any suggestions or solutions, I'd really appreciate it. The rails_admin wiki is not as helpful for this specific type of thing and I've poured over it already.

If you need more clarification or my question/code is not clear enough, please ask.

Aucun commentaire:

Enregistrer un commentaire