Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use ransack on delegated fields

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?

like image 545
Boti Avatar asked Apr 23 '13 13:04

Boti


1 Answers

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

like image 104
Danny Ocean Avatar answered Nov 09 '22 02:11

Danny Ocean