How can I make rails-admin work with associations?

665 views
Skip to first unread message

patrick99e99

unread,
Jun 16, 2011, 12:30:43 PM6/16/11
to rails_admin
Two questions:

1) How can I make a column in the 'list' for a model consist of data
from the record's association? In otherwords, I have a user model and
a user has_many posts.. I want to simply have a "post count" column in
the list. I tried doing:

field :posts do
formatted_value do
value.count
end
end
but that results in a divide by zero error... I even tried doing:

field :posts do
formatted_value do
bindings[:object].posts.count
end
end
but got the same results.

2) How can I filter the listing to a particular scope? For example, I
want to make the users post count be a link that is clickable which
will show all posts for the given user...

The best I could figure out how to do this was to do:

# note that I created a method post_count to temporarily solve problem
#1
field :post_count do
formatted_value do
bindings[:view].link_to value, "/admin/posts?
query=#{bindings[:object].id}"
end
end
Which doesn't work very well... Is there a way to instruct rails-admin
to do a .where(:user_id => xxx) on the model?

The other thing I wasn't crazy about was having to manually put in
'admin/posts'.. I was trying to see if I could do
rails_admin_list_path(:model_name => "posts").. but that didn't seem
to work.

Benoit Bénézech

unread,
Jun 17, 2011, 9:28:45 AM6/17/11
to rails...@googlegroups.com
You're messing with the formatting of the column output, this won't do you any good.
If you have specific needs for any field, the easiest way around is too change the partial being displayed to a new one you'll create in your app/views/rails_admin/main application folder. There's a word about that in the readme.

For your second problem, the proper way should be to override the method that sends the list of results. But I'm not sure it will work right now, because of ajax loading related stuff.
Reply all
Reply to author
Forward
0 new messages