create_table "comments", force: true do |t|
t.integer "movie_id"
t.string "user_comment"
t.string "user"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "movies", force: true do |t|
t.string "title"
t.integer "year"
t.text "cast"
t.string "director"
t.string "category"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "like"
t.integer "dislike"
t.string "genre"
t.integer "rating"
end
end
我有两个模特,电影&评论 模型/ movie.rb
class Movie < ActiveRecord::Base
has_many :comments
include Tire::Model::Search
include Tire::Model::Callbacks
after_touch() { tire.update_index }
mapping do
indexes :title,boost: 100
indexes :year,:analyzer => 'snowball'
indexes :cast,:analyzer => 'snowball'
indexes :user_comment
end
def self.search(params)
tire.search(load: true) do |s|
s.query {string "*#{params[:query]}*"} if params[:query].present?
s.filter :range,year: {lte: 2004}
end
end
def to_indexed_json
to_json(methods: [:user_comment])
end
def user_comment
movie.comments.user_comment
end
end
模型/ comment.rb
class Comment < ActiveRecord::Base
belongs_to :movie,touch: true
end
搜索控制器以搜索查询。 控制器/ search_controller.rb
class SearchController < ApplicationController
def index
if(params[:query]).present?
@results=Movie.search(params)
else
@results=[]
end
end
end
视图/搜索/ index.html.erb
<h1>Search#index</h1>
<p>Find me in app/views/search/index.html.erb</p>
<%= form_tag search_index_path, method: :get do %>
<p>
<%= text_field_tag :query, params[:query] %>
<%= submit_tag "Search", name: nil %>
</p>
<% end %>
<% if @results %>
<% @results.each do |fetchresults| %>
<%= fetchresults.title %>
<%= fetchresults.year %>
<%= fetchresults.director %>
<br/>
<% end %>
<% end %>
我正在尝试使用轮胎在电影控制器中搜索评论。 当我试图运行命令时: - rake environment tire:import CLASS =“Movie”FORCE =“true”
显示错误: -
[IMPORT] Deleting index 'movies'
[IMPORT] Creating index 'movies' with mapping:
{"movie":{"properties":{"title":{"boost":100,"type":"string"},"year":{"analyzer":"snowball","type":"string"},"cast":{"analyzer":"snowball","type":"string"},"user_comment":{"type":"string"}}}}
rake aborted! 5% ||| | ETA: 00:00:03
undefined local variable or method `movie' for #<Movie:0x0000000337c5c8>
/home/user/Desktop/abc/elasticsearch/elastictest/app/models/movie.rb:36:in `user_comment'
/home/user/Desktop/abc/elasticsearch/elastictest/app/models/movie.rb:32:in `to_indexed_json'
Tasks: TOP => tire:import => tire:import:model
(See full trace by running task with --trace)
任何人都可以帮助我。
我的任务是从评论表中搜索评论。
&安培;还有一件事是如何在我的视图中获得该评论的电影ID。
感谢。
答案 0 :(得分:0)
似乎问题在于您的方法
def user_comment
movie.comments.user_comment
end
应该是
def user_comment
comments.user_comment
end