简体   繁体   中英

How to get vanity_url resolved in ActiveAdmin belongs_to?

I'm adding ActiveAdmin to a mature application and having difficulty getting the route generation to work for a belongs_to relationship. Here is the class relationship:

class Project < ActiveRecord::Base
  def to_param
     vanity_url.blank? ? id.to_s : vanity_url
  end
end

class Job < ActiveRecord::Base
  belongs_to :project
end

This is important because we use routes such as domain/projects/awesome_project instead of domain/projects/215 . All pretty standard stuff.

In ActiveRecord, I've gotten the relation correctly defined with:

ActiveAdmin.register Project do
end

ActiveAdmin.register Job do
  belongs_to :project
end

I believe this is correct because the route generated include:

admin_project_jobs     GET      /admin/projects/:project_id/jobs(.:format)                                      admin/jobs#index
                       POST     /admin/projects/:project_id/jobs(.:format)                                      admin/jobs#create
new_admin_project_job  GET      /admin/projects/:project_id/jobs/new(.:format)                                  admin/jobs#new
edit_admin_project_job GET      /admin/projects/:project_id/jobs/:id/edit(.:format)                             admin/jobs#edit
admin_project_job      GET      /admin/projects/:project_id/jobs/:id(.:format)                                  admin/jobs#show
... etc

When I use a route generator, such as admin_project_jobs_path(@project) , the correct route is generated; that is: /admin/projects/awesome_project/jobs .

The problem is that with in the ActiveAdmin Jobs controller, the project_id value of "awesome_project" is does not result in the correct parent object. If I change the route generation to admin_project_jobs_path(@project.id) to use the ID of the object instead of it's vanity_url, that results in a path like /admin/projects/215/jobs , which is correctly resolved. However ActiveAdmin generates other paths and those use the object, which resolve back to the vanity_url, so I can't side step this problem forever.

I've read through the code to see where the path is generated, but it seems the real solution should be in the Project or the Job ActiveAdmin object. I've tried putting custom find_resource blocks into both, but haven't found something that does what is should.

Has anyone worked with such a scenario, or understands more about how the ActiveAdmin resources are resolved? Thanks.

ActiveAdmin.register Job do
  belongs_to :project, :finder => :find_by_title! # or what can find your model
end

For more details see https://github.com/josevalim/inherited_resources#belongs-to

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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