diff --git a/app/controllers/search_controller.rb b/app/controllers/search_controller.rb new file mode 100644 index 0000000..91d60a1 --- /dev/null +++ b/app/controllers/search_controller.rb @@ -0,0 +1,28 @@ +# coding: utf-8 +class SearchController < ApplicationController + + def index + if params[:format] == "json" + result = Ask.search_title(params["w"],:limit => 10) + puts result[:words] + simple_items = result[:items].collect do |item| + {:topics => item.topics, + :title => item.title, + :_id => item.id} + end + render :json => simple_items.to_json + else + @asks = Ask.search_title(params["w"],:limit => 20)[:items] + set_seo_meta("关于“#{params[:w]}”的搜索结果") + render "/asks/index" + end + end + + def topics + if params[:format] == "json" + @topics = Topic.search_name(params[:w],:limit => 10) + render :json => @topics.to_json(:only => [:id,:name]) + end + + end +end diff --git a/app/models/ask.rb b/app/models/ask.rb index 63b3003..528cac3 100644 --- a/app/models/ask.rb +++ b/app/models/ask.rb @@ -18,6 +18,7 @@ class Ask field :last_updated_at, :type => DateTime index :topics + index :title # 提问人 belongs_to :user, :inverse_of => :asks diff --git a/app/models/topic.rb b/app/models/topic.rb index 334f881..f7ac895 100644 --- a/app/models/topic.rb +++ b/app/models/topic.rb @@ -42,4 +42,9 @@ def self.save_topics(topics, current_user_id) def self.find_by_name(name) find(:first,:conditions => {:name => name}) end + + def self.search_name(name, options = {}) + limit = options[:limit] || 10 + where(:name => /#{name}/i ).desc(:asks_count).limit(limit) + end end diff --git a/app/views/layouts/application.html.erb b/app/views/layouts/application.html.erb index e867fc9..99d623b 100644 --- a/app/views/layouts/application.html.erb +++ b/app/views/layouts/application.html.erb @@ -1,4 +1,4 @@ -<%= spaceless do %> +<% spaceless do %> @@ -43,7 +43,7 @@ cachedItems = searchCache.get(t); if(cachedItems == null){ $.ajax({ - url : "<%= search_asks_path(:format => 'json') %>", + url : "/search.json", data : { w : t }, dataType : "json", success : function(res){ @@ -74,7 +74,7 @@ html += ''+item_title+''; html += ''; } - html += '