'Ransack search with two belongs_to associations to the same model

I have the following models:

class Item < ApplicationRecord
  belongs_to :category
  belongs_to :manufacturer, class_name: "Origin"
  belongs_to :purchased_from, class_name: "Origin"
  belongs_to :location

  UNRANSACKABLE_ATTRIBUTES = %w[id created_at updated_at location_id category_id manufacturer_id purchased_from_id ] 

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + [:location_name, :category_name, :manufacturer_name, :purchased_from_name] + _ransackers.keys
  end

end

class Origin < ApplicationRecord
  UNRANSACKABLE_ATTRIBUTES = %w[id created_at updated_at ] 

  def self.ransackable_attributes auth_object = nil
    (column_names - UNRANSACKABLE_ATTRIBUTES) + _ransackers.keys
  end

end

with two associations to the same table. I want to be able to search on either the "manufacturer_name" or "purchased_from_name". In the items_controller I have:

  def index
    @search = Item.ransack(params[:q])
    @search.sorts = 'category_name asc' if @search.sorts.empty?
    @items = @search.result.includes(:category, :location, :manufacturer, :purchased_from).page(params[:page]).per(3)
    @search.build_condition
  end

The searches work exactly as I intend, with Ransack joining the origins table on either the manufacturer_id or the purchased_from_id as appropriate. The problem I am having is with the pull-down menu on the search form. The attribute_select is providing a menu with two identical items corresponding to the "name" field of the Origin model. If I select the first of these the search is on the manufacturer_name and if I select the second it is on the purchased_from_name just as I want. But how do I make them display differently? Customizing the attribute names in the locale/en.yml file doesn't help because Ransack is using the same model Origin in both cases. For example, with the following:

en:
  ransack:
    attributes:
      location:
        name: "Location"
      category:
        name: "Category"
      manufacturer:
        name: "Manufacturer"
      purchased_from:
        name: "Purchased from"
      origin:
        name: "man or pfrom"

the "manufacturer" and "purchased_from" entries are ignored and both menu items show as "man or pfrom".



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source