使用Datamapper和Sinatra进行简单搜索

时间:2011-04-21 17:32:25

标签: ruby search sinatra datamapper

我对Ruby和后端开发一般都很陌生。话虽这么说,我正在尝试创建一个简单的搜索表单。我使用Sinatra作为框架,使用Datamapper作为我的ORM。做这个的最好方式是什么?下面是我的架构我希望搜索操作同时搜索磁贴和类别。

require 'sinatra'
require 'datamapper'


DataMapper.setup(:default, "sqlite3://#{Dir.pwd}/cal.db")

class Event
  include DataMapper::Resource

  property :id,               Serial
  property :title,            String
  property :text,             Text
  property :contact_name,     String
  property :contact_email,    String
  property :location,         String
  property :event_start_time, String
  property :event_end_time,   String
  property :category,         String
  property :created_at,       DateTime
  property :approved,         Boolean, :default => false

end

DataMapper.auto_upgrade!


post '/search'  do
   @results = Event.all
   erb :layout
end

============ layout.erb

<form action="/search" method="post">
  <input type="text" name="query"/><br />   
  <input type="submit" />
</form>

<% if @results %>
    <table>
        <%@results.each do |r|%>
        <tr valign="top">
            <td><%=r.title%></td>
        </tr>
        <%end%>
    </table>
<% end %>

1 个答案:

答案 0 :(得分:7)

最基本的搜索查询可能是这样的:

@events = Event.all(:title.like => "%#{params[:query]}%") | Event.all(:category.like => "%#{params[:query]}%")