0

As per the often cited Justin Weiss article on scopes. The goal is that the titles of Articles can be searched by keyword, so that the query string ?title=kayne populates @articles.title with articles with kayne in the title.

class Article < Active Record::Base
  .
  .
  scope :title, -> (title) { where("title like ?", "%#{title}%")}
end

class ArticlesController < ApplicationController
  def index 
    @articles = Article.all
    @articles = @articles.title if params[:title].present? 
  end
end

Heroku Log
Parameters: {"title"=>"kayne"}
: Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
: ArgumentError (wrong number of arguments (0 for 1)):
2

2 Answers 2

1

With respect to your question that it requires to pass first words from sentense, please find my inputs as below:

scope :title, -> (title) { where("title like ?", "%#{title}%")}

When using Like operator it will fetch all matching records from entire sentense, doesn't bothering starting word or ending word.

It will returns all the records with empty params so in that case no need to check params present or not.

Sign up to request clarification or add additional context in comments.

3 Comments

This is working. Is there a way to make it so that capitalization does not matter? Right now it will only return Fried if you query for Fried. Thanks.
the above can be achieved by substituting ILIKE for like.
scope :title, -> (title) { where("title ilike ?", "%#{title}%")} - The key word ILIKE can be used instead of LIKE to make the match case-insensitive.
0
class ArticlesController < ApplicationController
  def index 
    @articles = Article.all
    @articles = @articles.title(params[:title]) if params[:title].present? 
  end
end

1 Comment

I guess this works however it only works if I am searching for the first word in the title... So for a title of Fried Eggs it only works if I pass the param of Fried.. even fried does not work... is there a way to do this so that it will work like a normal keyword search and not be limited to the very first word of the title string?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.