无法访问attr_accessor定义的变量 [英] Cannot access attr_accessor defined variables
问题描述
我使用的思考斯芬克斯运行搜索,我也得到了相应的ActiveRecord模型罚款。问题是,我想创建的每个模型的一个适当的链接路径和文本,然后将信息以JSON形式的浏览器,通过AJAX。我现在用的是下面建立这些连接属性:
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
高清build_ajax_response self.search_link = Rails.application.routes.url_helpers.tagged_item_path(self.id) self.search_text = self.name 结束 结束
def build_ajax_response self.search_link = Rails.application.routes.url_helpers.tagged_item_path(self.id) self.search_text = self.name end end
由此产生的JSON对象不具有任何列出的搜索_ *属性,更谈不上对他们的价值。我已经使用@search_link以及刚刚search_link在 build_ajax_response
方法试过了。
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?
推荐答案
Rails的默认 to_json
不知道这些额外的不活动记录属性您已经添加。最简单的可能的事情可能是指定它们作为额外的方法包括:
Rails' default to_json
doesn't know about those extra not 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] }
这篇关于无法访问attr_accessor定义的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!