【发布时间】:2012-10-10 13:23:41
【问题描述】:
@saverio 在Tagging from Scratch: the Tag Cloud Issue 上成功回答了这个数据库查询问题
现在我正在尝试将标记系统与 jQuery-tokenInput 连接到 Create 和 Find 动态标记,就像在http://railscasts.com/episodes/258-token-fields-revised 上一样。
- 我猜这是 Posgresql 数据库的查询问题。
- 我已经正确安装了 Postgresql
- jQuery-tokenInput 位于 Application.js
//= require jquery.tokeninput - 不知何故,它可以从数据库中已经存在的内容中加载标签,但它无法动态查询与 pictures.js.coffee 代码中列出的相同的单词。
遵循所有相关范围:
pictures.js.coffee
jQuery ->
$('#picture_tag_tokens').tokenInput '/tags.json'
theme: 'facebook'
prePopulate: $('#picture_tag_tokens').data('load')
/views/pictures/_form
<div class="field">
<%= f.label :tag_tokens, "Tags (separated by commas)" %><br />
<%= f.text_field :tag_tokens, data: {load: @picture.tags} %>
</div>
这里我的逻辑有点迷失了
/models/picture.rb
class Picture < ActiveRecord::Base
attr_accessible :description, :title, :tag_tokens
has_many :taggings
has_many :tags, through: :taggings
attr_reader :tag_tokens
#The **below** is the relevant part for the #view/pictures/_form
def tag_tokens=(tokens)
self.tag_ids = Tag.ids_from_tokens(tokens)
end
def self.tagged_with(name)
Tag.find_by_name!(name).pictures
end
def self.tag_counts
Tag.select("tags.*, count(taggings.tag_id) as count").
joins(:taggings).group("tags.id")
end
def tag_list
tags.map(&:name).join(", ")
end
def tag_list=(names)
self.tags = names.split(",").map do |n|
Tag.where(name: n.strip).first_or_create!
end
end
end
下面我可以弄清楚我无法查询数据库
/models/tag.rb
class Tag < ActiveRecord::Base
attr_accessible :name
has_many :taggings
has_many :pictures, through: :taggings
def self.tokens(query)
tags = where("name like ?", "%#{query}%")
if tags.empty?
[{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
else
tags
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
end
我设置标签控制器行为的方式也是如此
#controllers/tags_controller.rb
class TagsController < ApplicationController
def index
@tags = Tag.all
respond_to do |format|
format.html
format.json { render json: @tags.tokens(params[:q]) }
end
end
end
那么,为什么我无法查询 Postgresql 并且无法动态创建或查找?
【问题讨论】:
标签: ruby-on-rails postgresql tagging acts-as-taggable-on jquery-tokeninput