【问题标题】:Rails ActiveAdmin and has_many associationRails ActiveAdmin 和 has_many 关联
【发布时间】:2013-02-05 12:07:46
【问题描述】:

我对 active_admin 还很陌生,我想知道是否有办法实现以下目标

我有两个模型

User
  belongs_to :group

Group
 has_many :users

我已经成功地在 activeadmin 中为组和用户创建了页面,现在我想要显示属于某个组的用户。我在组索引页面上有按钮 manage_members 应该只显示该组的成员。我可以从组中删除成员或添加更多成员。

这就是我目前能够做到的事情

member_action :manage_members do
    @group = Group.find(params[:id])
    @page_title = "Manage Groups > @#{@group.name}, Edit Members"
end

还有一个视图 app/vies/admin/groups/manage_users.html.arb

table_for assigns[:group].users do
  column "Name" do |u|
    u.user_id
  end
  column "email" do |u|
    u.user.email
  end
  column "Created Date" do |u|
    u.user.created_at
  end

  column "OfficePhone" do |u|
    u.user.office_no
  end
end

这显示了组的成员,但我必须在此页面上完成所有工作才能添加编辑删除成员,我不能在这里有 active_admin 过滤器和其他很酷的东西,这就像一个自定义页面,

有没有办法拥有一个索引页面(具有过滤器批处理操作等所有优点)(就像用户一样),但只显示一个组的用户。类似于范围索引页面,它显示在组中的用户上,我对该页面具有与任何活动管理索引页面相同的控制权?更像下图

而不必做我自己目前看起来像的所有工作

对 active_admin 来说非常陌生,如果我遗漏了一些非常直截了当的内容,我们深表歉意。

谢谢

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 activeadmin


    【解决方案1】:

    也许过滤器就可以了。看起来像(把它放在你放置 member_action 的同一个文件中)

    filter :group, :as => :select, :collection => proc { Group.for_select }
    

    proc 用于确保对组的更改(添加/删除/..)立即反映到过滤器中的选择列表。这与生产中的类缓存有关。 不要忘记将此范围放入您的 Group 模型中。

    scope :for_select, :select => [:id, :name], :order => ['name asc']
    

    另一种方法是使用作用域。如果您的 Group 模型中有一个字段,例如可以用作方法标头的 slug/label,那么您可以在您的 activeadmin 用户注册块中执行类似的操作:

    Group.all.each do |group|
      # note the sanitization of the Group name in the gsub
      scope "#{group.name.gsub(/-/,'_')}".to_sym
    end
    

    这在你的用户模型中:

    Group.all.each do |group|
      # note the sanitization of the Group name in the gsub
      scope "#{group.name.gsub(/-/,'_')}".to_sym, joins(:group).where("group.name = ?",role.name)  
      # using joins(:group) or joins(:groups) makes a difference,
      # so not sure as I have not tested, but maybe the where should be
      # ....where("groups.name = ....
    end
    

    它应该在索引视图上方为您提供漂亮的按钮,如下所示:http://demo.activeadmin.info/admin/orders

    如果你想要这个 has_and_belongs_to_many 关系,我建议你看看这个Rails3 Active Admin - How to filter only records that meet all checked items in collection

    祝你好运!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多