0

Probably a silly question, so I apologize in advance for this:

I have an Item Controller whose index action I'm using to show all items (duh). Now, I want to filter the items that are shown (here, just ones that have 'shoes' in their titles).

Unfortunately, I am not able to define the @item = Item.find(params[:id]) statement under the index action.

I am getting the dreaded ActiveRecord::RecordNotFound in ItemsController#index ---- Couldn't find Item without an ID error.

Any ideas?

Items Controller

def index
     @item = Item.find(params[:id])
     @items = Item.where(@item.title =~ /shoes/i).paginate(:page => params[:page], :per_page => 30)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @items }
    end
  end
abhir
  • 1,059
  • 1
  • 9
  • 25

1 Answers1

5

This is actually what you want. What you tried makes no sense.

  def index
     @items = Item.where("title ILIKE '%shoes%'").paginate(:page => params[:page], :per_page => 30)

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @items }
    end
  end

Edit:

In a way to be compatible with all the supported DBs it seems you can do something like this instead

item=Item.arel_table
Item.where(item[:title].matches('%shoes%'))
Ismael Abreu
  • 16,443
  • 6
  • 61
  • 75
  • 1
    The existence of ILIKE (and the case sensitivity of LIKE) is database specific so you usually [need a bit of hackery](http://stackoverflow.com/a/203419/479863) if you care about a portable solution. AFAIK, ILIKE is PostgreSQL-specific. That said, you're on the right track. – mu is too short Nov 12 '12 at 02:31
  • Sick - this works.Could you explain what you did? (mainly the "title ILIKE '%shoes%'" portion? – abhir Nov 12 '12 at 02:32
  • Is there a RegEx way of doing it that is applicable all-around? – abhir Nov 12 '12 at 02:32
  • 1
    Well, I see the LIKE or ILIKE as a way to use some kind of regex in a SQL query, in this case it's postgresql specific as @muistooshort said. Here is some info about it http://www.postgresql.org/docs/7.3/static/functions-matching.html – Ismael Abreu Nov 12 '12 at 02:41
  • 2
    @abhir: Most databases support real regexes in one form or another but, alas, they all do it differently. And you probably want to look at the current version of the PostgreSQL docs, 7.3 is rather long in the tooth: http://www.postgresql.org/docs/current/static/functions-matching.html – mu is too short Nov 12 '12 at 03:01