Search code examples
ruby-on-railsarrayssqliteransack

Rails Ransack - removing element from array


I'm learning how to use ransack, so I have a problem there I'm not sure if it is because the ransack or if it is because the array.

I have a form with 2 text fields (:search and :discipline). So I'm trying do a search using the 1º field parameter AND the 2º field parameter.

The idea is search for all elements that comes from the 1º parameter (field :search, and then remove all the elements that are different from the 2º parameter (field :discipline).

class PagesController < ApplicationController
  def home
    @rooms = Room.limit(6)
  end

  def search

    if params[:search].present? && params[:search].strip != ""
        session[:loc_search] = params[:search]
    end

    if params[:discipline].present? && params[:discipline].strip != ""
      session[:loc_discipline] = params[:discipline]
    end

    arrResult = Array.new

    if session[:loc_search] && session[:loc_search] != ""
        @rooms_address = Room.where(active: true).near(session[:loc_search], 5, order: 'distance')       
    else
        @rooms_address = Room.where(active: true).all
    end

    @search = @rooms_address.ransack(params[:q])
    @rooms = @search.result

    @arrRooms = @rooms.to_a


    if (session[:loc_discipline] && !session[:loc_discipline].empty?)

      @rooms.each do |room|

        not_available = Room.where(
            "(room_type != ?)",
            session[:loc_discipline]
          )

        if not_available.length > 0          
          @arrRooms.delete(room)  
        end 
      end
    end     
  end
end

My @arrRooms is returning NULL after I try do this @arrRooms.delete(room). I dont know if have a better way to do this, but I'm trying do it like a tutorial that I found.


Solution

  • I assume that you're trying to show all rooms that are not available?

    I think the best strategy is to load what you really want, and not loading everything an then deleting the things you don't need. Your code is really hard to read, I suggest you take a little tutorial like this: http://tryruby.org/levels/1/challenges/0, or this: https://www.codeschool.com/courses/ruby-bits

    Try extracting code like where(active: true) into a scope like:

    class Room < ActiveRecord::Base
      scope :active, -> { where(active: true) }
      scope :available, -> (discipline) { where.not(room_type: discipline) }
    end
    

    In your controller you can then make this:

    def index 
      @rooms = Room.active.available(params[:discipline])
      search_param = params[:search].present?
      if search_param.present?
        @rooms = @rooms.near(session[:loc_search], 5, order: 'distance')
      end
      @rooms = @rooms.ransack(params[:q]).result(distinct: true)
    end
    

    This is what I could guess out of your code.