Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Selecting associated models #156

Open
yorickvandervis opened this issue Oct 15, 2022 · 3 comments
Open

Selecting associated models #156

yorickvandervis opened this issue Oct 15, 2022 · 3 comments

Comments

@yorickvandervis
Copy link

I was wondering if it was possible to enable using associated models during creation. For example, I am trying to create a model which has some associations. It's an Activity model which belongs_to an ActivityCategory model. During creation on the /madmin panel I can't select any category. Same goes other way around. Is there a way to select these?

@tolaseadegbite
Copy link

@excid3

@bbonamin
Copy link

This would be a huge timesaver for us, I'm having to edit all forms of models that have associations in order to get this feature. Perhaps the association scope could be an option of the attribute method when defining the resource? Or perhaps it could default to Model.all to at least get something usable out of the box.

@dapicester
Copy link

I have been able to workaround this with a custom field. It is a very quick'n dirty patch but it works for me.

Here is the code for the belongs_to association:

class BelongsTo < Madmin::Fields::BelongsTo
  def options_for_select(record)
    all_options_for class_for_association record
  end

  private

    def class_for_association(record)
      record.class
        .reflect_on_all_associations(:belongs_to)
        .find { |el| el.name == attribute_name }
        .klass
    end

    def all_options_for(klass)
      resource = Madmin.resource_by_name klass.name
      sorting = sorting_for resource
      klass.all.order(sorting).map do |record|
        [ resource.display_name(record), record.id ]
      end
    end

    def sorting_for(resource)
      column = resource.try :default_sort_column
      direction = resource.try :default_sort_direction || "desc"

      "#{column} #{direction}"
    end
end

Then in your resource specify to use the field:

class FooResource < Madmin::Resource
  attribute :bar, field: BelongsTo
  # ...
end

There are a few issue with my code, the most important is that it loads all the records for the association.
In my I have very few records, so it's fine. Please keep that in mind if using that.
Also, you don't get any fancy select. I am not sure if this changed recently, as I remember seeing some JS-powered select supporting search and completion.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants