我使用this教程从头开始在Ruby on Rails中实现了标记云。
当您点击我的照片博客上的标签时,请说东京,列出所有标有 Tokyo 的照片。我现在想要添加两件事来使我的标签云更具动态性,这样它就可以缩小列表范围:
我是Ruby的新手,无论我尝试过什么,都无法完成其中任何一项(这里列出的内容太多了)。
以下是相关代码:
photo.rb:
class Photo < ActiveRecord::Base
belongs_to :photo
has_many :taggings, dependent: :destroy
has_many :tags, through: :taggings
accepts_nested_attributes_for :tags
def self.tagged_with(name)
Tag.find_by_name!(name).photos
end
def self.tag_counts
Tag.select("tags.*, count(taggings.tag_id) as count").
joins(:taggings).group("taggings.tag_id")
end
tag.rb:
class Tag < ActiveRecord::Base
has_many :taggings
has_many :photos, through: :taggings
end
tagging.rb:
class Tagging < ActiveRecord::Base
belongs_to :tag
belongs_to :photo
end
application_helper.rb:
module ApplicationHelper
def tag_cloud(tags, classes)
max = 0
tags.each do |t|
if t.count.to_i > max
max = t.count.to_i
end
end
tags.each do |tag|
index = tag.count.to_f / max * (classes.size - 1)
yield(tag, classes[index.round])
end
end
end
photos_controller.rb:
class PhotosController < ApplicationController
def index
if params[:tag]
@photos = Photo.tagged_with(params[:tag])
else
@photos = Photo.order("created_at desc").limit(8)
end
end
private
def set_photo
@photo = Photo.find(params[:id])
end
def photo_params
params.require(:photo).permit(:name, :description, :picture, :tag_list, tags_attributes: :name)
end
end
index.html.erb:
<div id="tag_cloud">
<% tag_cloud Photo.tag_counts, %w[xxs xs s m l xl xxl] do |tag, css_class| %>
<%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>
</div>
photos.css.scss:
#tag_cloud {
width: 400px;
line-height: 1.6em;
.xxs { font-size: 0.8em; COLOR: #c3c4c4; }
.xs { font-size: 1.0em; COLOR: #b9bdbd; }
.s { font-size: 1.2em; COLOR: #b0b5b5; }
.m { font-size: 1.4em; COLOR: #9da6a6; }
.l { font-size: 1.6em; COLOR: #8a9797; }
.xl { font-size: 1.8em; COLOR: #809090; }
.xxl { font-size: 2.0em; COLOR: #778888; }
}
非常感谢任何帮助!
答案 0 :(得分:1)
如果我理解正确,您希望有可能选择标记有一个或多个标签的照片。你需要改变你的功能:
def self.tagged_with(*names)
joins(:tags).where(tags: { name: names })
end
param的名字:
def index
if params[:tags]
@photos = Photo.tagged_with(params[:tags])
else
@photos = Photo.order("created_at desc").limit(8)
end
end
在视图中,当您定义方法current_tags
时:
<div id="tag_cloud">
<% tag_cloud Photo.tag_counts, %w[xxs xs s m l xl xxl] do |tag, css_class| %>
<%= link_to tag.name, tag_path([tag.name, *current_tags].uniq), class: css_class %>
<% end %>
</div>