How to use ransack on delegated fields
Asked Answered
M

1

9

I have the following model

class Position < ActiveRecord::Base

  belongs_to :position_name
  delegate :name, to: :position_name

And this search form

  = search_form_for @search, url: '#', method: 'GET', html: {id: nil, class: "term_search_form"}  do |f|
      = f.text_field :name_cont, class: 'search-query', id: nil, placeholder: t('search')

And I still receive this error message:

undefined method `name_cont' for #<Ransack::Search:0x007f97187c5b80>

I think it is because of the delegated method name.

How can I use ransack on delegated methods?

Michael answered 23/4, 2013 at 13:33 Comment(0)
A
7

It is kinda late answer, but maybe it will help someone else. So, I had a similar issue.

I had 3 models: area, building and product, where area has_many :buildings, buildings has_many :products. In my product model I used delegate :area_id, to: :building.

I used ransack to search a product by such fields like name, area, building. In my controller's action @search variable included associated Buiding model, like that:

@search = Product.includes(:building).search(params[:q])

So my search_form was like

= search_form_for @search, url: user_products_path do |f|
  %td
  %td= f.text_field :name_cont, class: "form-control", placeholder: t('.name')
  %td= f.select :building_area_id_eq, options_for_select(Area.data_for_select(true), q_param(:building_area_id_eq))
  %td= f.select :building_id_eq, options_for_select(Building.data_for_select(true), q_param(:building_id_eq))

That is, if in your controller you have included associated model :position_name, than in your view you should use = f.text_field :position_name_name_cont

Ames answered 25/9, 2014 at 15:4 Comment(3)
Is there a way to do this without the prefix? Like: area_id_eq.Sfax
@Sfax I don't think soAmes
Thank you for putting this up - 7 years later, it still helped me out!Warehouseman

© 2022 - 2024 — McMap. All rights reserved.