开发者

Multi-column Simple-Search from SQLite to Heroku/PostgreSQL

开发者 https://www.devze.com 2023-01-28 16:07 出处:网络
def self.search(search) if search where(\'name OR username OR bio LIKE ?\', \"%#{search}%\") else scoped end
def self.search(search)
  if search
    where('name OR username OR bio LIKE ?', "%#{search}%")
  else
    scoped
  end
end

The above code works fine on my development se开发者_如何学Pythonrver using SQLite, but since Heroku uses PostgreSQL it breaks (seems you can only use "OR" in truly boolean queries).

Is there a better way to implement this simple search so it works with PostgreSQL or do I have to move to a more complex search solution?


Are you looking for something like this?

def self.search(search)
  if search
    where('name IS NOT NULL OR username IS NOT NULL OR bio LIKE ?', "%#{search}%")
  else
    scoped
  end
end

If name and username can be NULL or empty then you'll want to use COALESCE:

def self.search(search)
  if search
    where("COALESCE(name, '') <> '' OR COALESCE(username, '') <> '' OR bio LIKE ?", "%#{search}%")
  else
    scoped
  end
end

These should work the same in SQLite and PostgreSQL.

0

精彩评论

暂无评论...
验证码 换一张
取 消