Cannot access attr_accessor defined variables

半城伤御伤魂 提交于 2019-12-01 17:14:49

问题


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?


回答1:


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]) }


来源:https://stackoverflow.com/questions/11435768/cannot-access-attr-accessor-defined-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!