我正在使用 Thinking Sphinx 来运行搜索,并且我得到了适当的 ActiveRecord 模型。问题是,我想在每个模型上创建适当的链接路径和文本,然后通过 AJAX 将信息以 JSON 形式发送到浏览器。我使用以下内容来构建这些链接属性:
在控制器中:
class FindController < ApplicationController
def tag_results
@results = ThinkingSphinx.search(params[:terms])
@results.each do |result|
result.build_ajax_response
end
respond_to do |format|
format.html
format.json { render :json => @results }
end
end
end
在模型中:
class TaggedItem < ActiveRecord::Base
attr_accessible :name
attr_accessor :search_link, :search_text
def build_ajax_response
self.search_link = Rails.application.routes.url_helpers.tagged_item_path(self.id)
self.search_text = self.名称
结尾
结尾
Rails 的默认设置to_json
不知道您添加的那些额外的非活动记录属性。最简单的可能是将它们指定为额外的方法来包括:
format.json { render :json => @results.to_json(:methods => [:search_link, :search_text]) }
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)