ActiveAdmin嵌套的自定义资源检索 [英] ActiveAdmin nested custom resource retrieval

查看:83
本文介绍了ActiveAdmin嵌套的自定义资源检索的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个具有belongs_to关系的模型。这两个模型都将自定义的to_param方法设置为使用资源密钥而不是实际ID

I have a couple models with a belongs_to relationship. The models both have custom to_param methods set to use a resource key instead of the actual id

def to_param
  return self.resource_key
end

对于我的管理模型,我有:

for my admin models, I have:

ActiveAdmin.register Foo do

  controller do
    def find_resource
      Foo.find_by(resource_key: params[:id])
    end
  end

  panel "Bars" do
  table_for foo.bars do
    column "Title" do |bar|
      link_to bar.title, admin_foo_bar_path(foo, bar)
    end
  end
end

end

ActiveAdmin.register Bar do
  belongs_to :foo

  controller do
    def find_resource
     Bar.find_by(resource_key: params[:id])
    end
  end
end

Foo正常运行,所有链接都是使用URL路径中的resource_key生成的。同样,也为Bar正确生成了URL,但是当我尝试打开Bar项时,收到如下消息:
找不到id = {resource_id} 的Foo。

Foo works fine, all links are generated with the resource_key in the URL path. The URL is generated correctly for Bar, as well, but when I attempt to open the Bar item I get a message like: Couldn't find Foo with id={resource_id}

我实际上在Bar视图上根本不需要Foo值,Bar资源键足以查询数据。我要么需要告诉应用程序不要尝试查找Foo值,要么将Bar设置为通过resource_key而不是id正确查询Foo。

I actually don't need the Foo value at all on my Bar view, the Bar resource key is enough data to query on. I either need to tell the app not to try to look up the Foo value, or set Bar to query Foo properly by resource_key instead of id.

我正在将Rails 4与AA的1.0主分支一起使用。

I'm using Rails 4 with the 1.0 master branch of AA.

推荐答案

两个可能的修复程序

1)尝试在belongs_to语句中使用可选

1) Try to use optional in belongs_to statement

 belongs_to :foo, :optional => true #it gives you urls for Bar without Foo

2)AA使用Inherited_resources gem,尝试自定义属地(默认情况下,它使用id查找)

2) AA use Inherited_resources gem , try to customize belongs_to (by default it uses find by id)

Inherited_resources示例

Example from inherited_resources

belongs_to accepts several options to be able to configure the association. For example, if you want urls like "/projects/:project_title/tasks", you can customize how InheritedResources find your projects:

class TasksController < InheritedResources::Base
  belongs_to :project, :finder => :find_by_title!, :param => :project_title
end

所以这应该有帮助

belongs_to :foo , :finder => :find_by_resource_key!

这篇关于ActiveAdmin嵌套的自定义资源检索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆