使用简单搜索时出现ActiveRecord错误

时间:2015-03-11 11:15:34

标签: ruby-on-rails ruby activerecord

我是Ruby on Rails的新手,并尝试为我的应用程序创建一个简单的搜索功能。搜索功能不断返回此ActiveRecord错误(这里我在“from”中搜索“london”):

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

型号:

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

控制器:

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

查看:

<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 %>

就像我说的那样,我在RoR很新,所以这甚至可能都是愚蠢的,但我真的很感激帮助。

1 个答案:

答案 0 :(得分:4)

问题是SQL中保留from。我强烈建议您重命名此字段,但如果您想按原样使用它 - self.where("\"from\" LIKE ?", "%#{search_from}%")