Search code examples
ruby-on-railsruby-on-rails-3ransack

Ransackable Attributes for has many relationship columns


I want to display has_many relationship columns in ransackable attributes list. So that I can display them in the dropdown.

I have a member model

class Member < ActiveRecord::Base
  has_many :memberships


 def self.ransackable_attributes(auth_object = nil)
  if auth_object == 'admin'
    super
  else
    super & ['first_name', 'last_name', 'license_number', 'memberships_membership_number_cont']
  end
 end

And membership model has some columns like membership_number which is unique and a string. Now in the dropdown of members listing page I want to provide membership_number, so that user can select membership_number from the dropdown and enter a value to search the respective member.

Any suggestions?

The dropdown I am taking about is:

enter image description here

PS: In the screenshot you may be looking for a dropdown for contains all/contain any ie options dropdown. I made is just one only contains any. Thats why its not visible.


Solution

  • You need to define the ransackable_attributes method in associated model for custom searchable attributes of that model. So your Membership model should be something like:

    class Membership < ActiveRecord::Base
      belongs_to :member
      ...
    
      def self.ransackable_attributes(auth_object = nil)
        ['membership_number', ...]
      end
    end
    

    And specify associations in ranssack form like:

    <%= f.condition_fields do |c| %>
      <%= c.attribute_fields do |a| %>
        <%= a.attribute_select associations: [:memberships] %>
      <% end %>
    <% end %>