Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
666 views
in Technique[技术] by (71.8m points)

ruby on rails - How do I link to a collection in rails_admin instead of individual items in a belongs_to?

I have a company that has many clients. By default when looking at the Companies tab, I have a field with Clients. Each client has his own separate link to a show page. I'm trying to wire it up so that I don't see each individual client as a link on the company show page, but instead a general link to 'Clients' index that belong to that company.

Here's the Company model

has_many :clients, class_name: 'Client', primary_key: 'friendlyName', foreign_key: 'shortname'

Here's the Client model

belongs_to :company, class_name: 'Company', foreign_key: 'shortname', primary_key: 'friendlyName'

The relationship seems to be set up correctly.

Here's what I've tried in rails_admin

  config.model 'Company' do
    exclude_fields :created_at, :updated_at
    object_label_method do
      :custom_label_method
    end
    
    list do
      field :all_clients do
        formatted_value do
          path = bindings[:view].index_path(model_name: 'Client', all_clients: bindings[:object].id)
          bindings[:view].link_to('Clients', path)
        end
      end
    end
  end

That's a code snippet that I've found and it does work to create a custom link to the Clients index page, but it doesn't take the belongs_to association into account.

question from:https://stackoverflow.com/questions/65910869/how-do-i-link-to-a-collection-in-rails-admin-instead-of-individual-items-in-a-be

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You are on the right track, you need the link to be built as RailsAdmin does it when filtering Client records in the index view by company. You need to do it manually once to figure out how the link is built. In an image this is what i mean

enter image description here

I added a filter and look at the url rails admin built.

Make sure you have the Client index config has the company field to be able to do it.

class Client < ApplicationRecord
  rails_admin do
    list do
      field :company do
        filterable true
      end
    end
  end
end

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...