Question

I am using Thinking Sphinx to run searches and I get the appropriate ActiveRecord Models fine. The problem is, I want to create an appropriate link path and text on each model, then send the info to the browser in the form of JSON, via AJAX. I am using the following to build those link attributes:

In the controller:

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
In the model:
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.name end end

The resulting json object doesn't have either of the search_* attributes listed, much less have a value for them. I've tried using @search_link as well as just search_link in the build_ajax_response method.

Am I doing this wrong? Could there be something else interfering?

Was it helpful?

Solution

Rails' default to_json doesn't know about those extra non active record attributes you've added. The easiest possible thing is probably to specify them as extra methods to include:

format.json { render :json => @results.to_json(:methods => [:search_link, :search_text]) }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top