jeudi 18 juin 2015

Custom Search in Ruby on Rails

I'm trying to implement a custom search feature in my Rails app.

I have 3 tables User Company and CompanyUser

My relations declared are as follows

class CompanyUser < ActiveRecord::Base

  belongs_to :company
  belongs_to :user
...
end

In Company.rb

has_many :company_users, dependent: :destroy
has_many :users, through: :company_users

In User.rb

has_many :company_users, dependent: :destroy
has_many :companies, through: :company_users

and in my view page I'm listing all companies using company_users table Now i have a search field where I can type a name in it which filters this list of company users.

I'm calling a method from my CompanyUsers table to filter the search result like this

@company_users = CompanyUser.all
if params[:search_data].present?
  @company_users = @company_users.filter_company_users(params[:search_data])
end

where params[:search_data] is passed to the same method when search data is entered in the search field.

this is the method that do the search filtering.

 def self.filter_company_users(search_data)
    where('company_id like (?)', "%#{search_data}%")
 end

Right now I can get the result only if I type the correct id of CompanyUser table in that search field. What I'm trying to do is to search using fields from User table and Company Table. For eg email from User and name from Company.

Aucun commentaire:

Enregistrer un commentaire