gpt4 book ai didi

ruby-on-rails - Ruby on Rails 中的动态标签云

转载 作者:数据小太阳 更新时间:2023-10-29 08:08:50 26 4
gpt4 key购买 nike

我使用 this 从零开始在 Ruby on Rails 中实现了标签云教程。

当你点击我的照片博客上的标签时,比如东京,所有带有东京标签的照片都会被列出。我现在想添加 2 个东西来让我的标签云更加动态,这样你就可以缩小列表的范围:

  • 标签云应该动态更新,这样它现在显示与剩余照片相关的标签,东京子集(字体大小相对于该子集缩放).
  • 当您单击此子集标签云中的标签时,比如 2008,我希望列出所有标记有东京 2008(而不是所有 标记为2008 的照片),最好无限

我是 Ruby 的新手,似乎无法完成其中任何一个,无论我尝试了什么(太多无法在此处列出)。

相关代码如下:

照片.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

标签.rb:

class Tag < ActiveRecord::Base
has_many :taggings
has_many :photos, through: :taggings
end

标记.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

照片 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>

照片.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; }
}

任何帮助将不胜感激!

最佳答案

如果我对您的理解正确,您希望有可能选择标记有多个标签之一的照片。你需要改变你的功能:

def self.tagged_with(*names)
joins(:tags).where(tags: { name: names })
end

参数名称:

def index
if params[:tags]
@photos = Photo.tagged_with(params[:tags])
else
@photos = Photo.order("created_at desc").limit(8)
end
end

并且在 View 中,当您定义方法 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>

关于ruby-on-rails - Ruby on Rails 中的动态标签云,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23401553/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com