Search code examples
ruby-on-railsransack

How do I get human names from ransack attributes


I am using ransack to build a search form:

<%= search_form_for @q do |f| %>

  <%= f.label :title_or_description_or_request_number_cont %>
  <%= f.search_field :title_or_description_or_request_number_cont %>

  <%= f.submit class: 'btn btn-info' %>
<% end %>

My model is called WorkRequest

The label for this displays the following text:

Title or Description or Request number contains

I want to use this text in output on the page when nothing is found - something like:

Unable to find a work request where Title or Description or Request number contains ...

I was hoping to use the human_attribute_name method to retrieve the text, but both of these:

WorkRequest.human_attribute_name :title_or_description_or_request_number_cont

WorkRequest.new.human_attribute_name :title_or_description_or_request_number_cont

Output: Title or description or request number cont

(ends 'cont' instead of 'contains')

How is label constructing its text output if it is not using human_attribute_name, and how can I construct the same text?

I know I can do a simple substitute of 'cont' for 'contains', but I want a solution that will modify the text output to match any ransack style search query (e.g. ones ending _eq)


Solution

  • I think I have a solution:

    context = Ransack::Context.for_class WorkRequest
    text =    Ransack::Translate.attribute(
               :title_or_description_or_request_number_cont, 
               context: context
              )
    

    That outputs:

    Title or Description or Request number contains