0

我有一个非常简单的 rails3 应用程序,我正在尝试学习如何使用 Tire::Model::Persistence 将 Elasticsearch 用作数据存储,但我在搜索时遇到问题(你知道,搜索)

这是我的模型:

class Post
  include Tire::Model::Persistence

  property :name
  property :published_on
end

这是我的路线:

Beta2::Application.routes.draw do
   root :to => 'posts#index'

  resources :posts
end

这是我的控制器:

class ContestsController < ApplicationController

  def index
    if params[:q].present?
      #@posts = Post.search(params[:q], load: true)
      @posts = Post.all
    else
      @posts = Post.all
    end

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @posts }
    end

  end
...show, edit, destroy...
end

我的 index.html.erb:

<h1>Listing posts</h1>

<%= form_tag posts_path, method: :get do %>
  <%= label_tag :query %>
  <%= text_field_tag :q, params[:q] %>
  <%= submit_tag :search, name: nil %>
<% end %>

<hr>

<table>
  <tr>
    <th>Name</th>
    <th>Published on</th>
    <th></th>
    <th></th>
    <th></th>
  </tr>

<% @posts.each do |post| %>
  <tr>
    <td><%= spot.name %></td>
    <td><%= post.published_on %></td>
    <td><%= link_to 'Show', post %></td>
    <td><%= link_to 'Edit', edit_contest_path(post) %></td>
    <td><%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %></td>
  </tr>
<% end %>
</table>
<br />

<%= link_to 'New Post', new_post_path %>
<%= link_to 'Back', posts_path if params[:q] %>

有了上面,只查看不带参数的 index 方法,渲染就好了。我已经注释掉了 if params[:q] 这样我就可以像正常旅行一样返回所有帖子

http://localhost:3000/

但是,一旦我点击该搜索按钮,我就会收到此错误消息:路由错误

没有路线匹配 {:action=>"show", :controller=>"posts"}

如果我将视图中的行删除到 <%= link_to ... %> 然后视图会呈现所有帖子的名称和发布文本。

如果我在控制器中更改:

#@posts = Post.search(params[:q], load: true)

回到

@posts = Post.search(params[:q], load: true)

并删除 Post.all

然后在模板中我收到以下错误:

undefined method `detect' for #<Post:0x00000003a61b40>

Extracted source (around line #21):

18:     <th></th>
19:   </tr>
20: 
21: <% @posts.each do |post| %>
22:   <tr>
23:     <td><%= post.name %></td>
24:     <td><%= post.published_on %></td>

可能有一件简单的事情我没有做,但我想不通,目前还没有一个很好的例子来说明只使用带轨道的轮胎作为唯一的数据存储,所以我不知道这是否只是人们的一个晦涩难懂的问题不使用 activerecord 时遇到。

4

1 回答 1

0

Post.search{query{term :name, params[:q]}} 匹配特定字段或
Post.search{query{string "#{params[:q]}"}} 匹配任何字段到整个字符串或
Post.search{query{wildcard "#{params[:q]}*"}} 将部分字符串匹配到任何字段

于 2012-09-18T19:59:20.353 回答