简体   繁体   English

如何获得rails_admin正确处理关联?

[英]how can I get rails_admin to handle associations properly?

Two questions: 两个问题:

1) How can I make a column in the 'list' for a model consist of data from the record's association? 1)如何在模型的“列表”中创建由记录关联数据组成的列? In other words, I have a user model and a user has_many posts. 换句话说,我有一个用户模型和一个用户has_many帖子。 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? 2)如何将列表过滤到特定范围? 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? 有没有一种方法可以指示rails-admin在模型上执行.where(:user_id => xxx)

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") . 我不担心的另一件事是必须手动输入'admin / posts ..'。我试图查看是否可以做rails_admin_list_path(:model_name => "posts") but that didn't seem to work. 但这似乎不起作用。

You'd probably get a better response on the rails_admin mailing list - http://groups.google.com/group/rails_admin/ 你可能会得到rails_admin邮件列表上更好的响应- http://groups.google.com/group/rails_admin/

For your first question, this should do the trick: 对于第一个问题,这应该可以解决问题:

field :posts, :virtual do
  formatted_value do
    bindings[:object].posts.count
  end
end

For your second question, rails_admin now has a filter system - see the "add filter" dropdown at http://demo.railsadmin.org/admin/players . 对于第二个问题,rails_admin现在具有过滤器系统-请参见http://demo.railsadmin.org/admin/players上的“添加过滤器”下拉列表。 Tapping into that would be a much better method. 利用该方法将是一种更好的方法。

rails_admin_list_path(:model_name => "posts") should work, you might have to include Rails.application.routes.url_helpers or similar. rails_admin_list_path(:model_name => "posts")应该可以工作,您可能必须include Rails.application.routes.url_helpers或类似名称。

Try adding this to your rails_admin.rb 尝试将其添加到rails_admin.rb

RailsAdmin.config {|c| c.label_methods << :field_name} 

worked for me 为我工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM