【问题标题】:ActiveAdmin nested custom resource retrievalActiveAdmin 嵌套自定义资源检索
【发布时间】:2014-03-19 03:27:35
【问题描述】:

我有几个具有belongs_to 关系的模型。模型都有自定义 to_param 方法设置为使用资源键而不是实际 id

def to_param
  return self.resource_key
end

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

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

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

我正在使用带有 AA 1.0 主分支的 Rails 4。

【问题讨论】:

  • 您的路线是如何定义的?你能分享他们的问题吗?
  • 对于AA,我只是使用默认的ActiveAdmin.routes(self)

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


【解决方案1】:

两种可能的修复方法

1) 尝试在 belongs_to 语句中使用 optional

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

2) AA 使用 Inherited_resources gem ,尝试自定义belongs_to(默认使用按id查找)

来自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!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-16
    • 1970-01-01
    • 2020-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多