我正在尝试通过模型搜索具有特定标签的所有记录。
我们正在尝试搜索的示例输出:
ruby-1.9.2-p0 :1 > Question.last.tags
=> [#<ActsAsTaggableOn::Tag id: 2, name: "preferences">, #<ActsAsTaggableOn::Tag id: 13, name: "travel">]
因此,
Question
具有偏好和旅行等tags
。我试过了:@tags = @questions.where("tags LIKE ?", "%#{params[:tags]}%")
=> []
@tags = @questions.where("tag LIKE ?", "%#{params[:tags]}%")
=> []
@tags = @questions.where("tag_list LIKE ?", "%#{params[:tags]}%")
=> BadFieldError: Unknown column 'tag_list'
当
params[:tags]
是“refere”或“ences”时,如何返回最高记录?问题模型
class Question < ActiveRecord::Base
has_many ...
acts_as_taggable_on :tags
end
第二次尝试
我刚刚创建了一个自定义 Controller 操作,以尝试按照@Nash的建议更改查询。我该如何纠正?
def autocomplete_question_tags
@tags = Question.tagged_with("%#{params[:term]}", :any => true)
respond_to do |format|
format.json
end
end
在表格中输入“旅行”后:
Started GET "/answers/autocomplete_question_tags?term=travel" for 127.0.0.1 at 2011-04-16 20:37:34 -0400
Processing by AnswersController#autocomplete_question_tags as JSON
Parameters: {"term"=>"travel"}
{"term"=>"travel", "action"=>"autocomplete_question_tags", "controller"=>"answers"}
SQL (1.8ms) SHOW TABLES
SQL (0.8ms) SELECT COUNT(*) AS count_id FROM (SELECT 1 FROM 'questions' WHERE (questions.id IN (SELECT taggings.taggable_id FROM taggings JOIN tags ON taggings.tag_id = tags.id AND (tags.name LIKE '%travel') WHERE taggings.taggable_type = 'Question'))) AS subquery
logger.debug: 1 result in query
Completed in 114ms
ActionView::MissingTemplate (Missing template answers/autocomplete_question_tags with {:handlers=>[:erb, :rjs, :builder, :rhtml, :rxml, :haml], :formats=>[:json], :locale=>[:en, :en]} in view paths "/Users/san/Documents/san/apl/app/views",
app/controllers/answers_controller.rb:36:in 'autocomplete_question_tags'
Rendered /Users/san/.rvm/gems/ruby-1.9.2-p0/gems/actionpack-3.0.1/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.7ms)
最佳答案
您可以允许参数搜索标记的任何部分。
Question.tagged_with("%#{params[:tags]}%", :any => true)
关于ruby-on-rails - 使用acts_as_taggable_on搜索,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/5685773/