habbala
habbala

Reputation: 5

ActiveRecord error when when using simple search

I'm very new at Ruby on Rails and trying to make a simple search function for my application. The search function keeps returning this ActiveRecord error (here I searched for "london" in "from"):

SQLite3::SQLException: near "from": syntax error: SELECT "journeys".* FROM "journeys" WHERE (from LIKE '%london%')

Model:

class Journey < ActiveRecord::Base
  validates :from, presence: true, length: { minimum: 1 }
  def self.search(search_from)
    self.where("from LIKE ?", "%#{search_from}%")
  end
end

Controller:

class JourneysController < ApplicationController
  def index
    @journeys = Journey.all
      if params[:search_from]
        @journeys = Journey.search(params[:search_from])
      else
        @journeys = Journey.all.order('created_at DESC')
    end
  end

View:

<p>
  <%= form_tag(journeys_path, :method => "get", from: "search-form") do %>
    <%= text_field_tag :search_from, params[:search_from], placeholder: "Search from", :class => 'input' %>
    <%= submit_tag "Search", :class => 'submit' %>
  <% end %>
</p>

<% if @journey.present? %>
  <%= render @journey %>
<% else %>
  <p>There is nobody going from <%= params[:search_from] %>.</p>
<% end %>

Like I said, I'm very new at RoR so this is probably stupid to even ask for, but I would really appreciate the help.

Upvotes: 0

Views: 33

Answers (1)

iced
iced

Reputation: 1572

Problem is that from is reserved in SQL. I highly suggest to rename this field, though if you want to use it as is - self.where("\"from\" LIKE ?", "%#{search_from}%").

Upvotes: 4

Related Questions