Question

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 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}

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.

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

Était-ce utile?

La solution

Two possible fixes

1) Try to use optional in belongs_to statement

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

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

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

So this should help

belongs_to :foo , :finder => :find_by_resource_key!
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top