Reputation: 2159
I have models User
and Article
.
User
has the following associations:
class User < ActiveRecord::Base
has_many :articles
and Article
's:
class Article < ActiveRecord::Base
belongs_to :user, required: true
I use rails_admin as a control panel and customize a required fields in rails_admin.rb
as follows:
config.model Article do
list do
field :id
field :title
field :user_id
field :created_at
end
end
But how to implement that instead of :user_id
displays the name of the user? I have a username
field in my database.
Thanks!
Upvotes: 1
Views: 799
Reputation: 34318
In your Article
model, you can add a custom method that will return the user_name
:
def user_name
self.user.username
end
Then, you can use this user_name
field in your admin like other model attributes:
config.model Article do
list do
field :id
field :title
field :created_at
field :user_name
end
end
Upvotes: 1
Reputation: 819
Here's another stab at it...
Rails_admin looks for a "name" or "title" field on the model, if there are none, it will display a somewhat ugly "User#1".
All you need to do in your User Model is to add the following method:
def title
try(:username)
end
I like to go back to this presentation for Rails Admin's best practices: http://www.slideshare.net/benoitbenezech/rails-admin-overbest-practices
It's a bit dated but everything you need is there (around page 14 for your case)
Upvotes: 0