【问题标题】:How to make a multi model tag_cloud with a join table?如何使用连接表制作多模型 tag_cloud?
【发布时间】:2015-08-21 14:33:59
【问题描述】:

我有一个联接表

create_table "combine_tags", force: true do |t|
  t.integer "user_id"
  t.integer "habit_id"
  t.integer "valuation_id"
  t.integer "goal_id"
  t.integer "quantified_id"
end

其目的是让 tag_cloud 为多个模型工作。我把它放在 application_controller

def tag_cloud
  @tags = CombineTag.tag_counts_on(:tags)
end

我的 tag_cloud 如下所示:

<% tag_cloud(@tags, %w(css1 css2 css3 css4)) do |tag, css_class| %>
  <%= link_to tag.name, tag_path(tag), :class => css_class %>
<% end %>

# or this depending on which works:

<% tag_cloud CombineTag.tag_counts, %w[s m l] do |tag, css_class| %>
  <%= link_to tag.name, tag_path(tag.name), class: css_class %>
<% end %>

我在所有模型的 _form 中都有这一行:&lt;%= f.text_field :tag_list %&gt;

combine_tags_helper

module CombineTagsHelper
  include ActsAsTaggableOn::TagsHelper
end

模型

class CombineTag < ActiveRecord::Base
  belongs_to :habit
  belongs_to :goal
  belongs_to :quantified
  belongs_to :valuation
  belongs_to :user
  acts_as_taggable
end

class Habit < ActiveRecord::Base # Same goes for other models
  has_many :combine_tags
  acts_as_taggable
end

如果您需要进一步的解释或 code 来帮助我,请告诉我 :)

【问题讨论】:

  • 您能简要告诉我您希望实现的具体行为是什么吗?
  • 我知道如何使用一个模型制作 tag_cloud,但我无法让它与多个模型一起使用,如果我在 tag_cloud 的习惯和目标下创建了一个名为 run 的标签按比例表示标签的使用情况。这对@ArupRakshit 有帮助吗?
  • 你能简单介绍一下用例吗?为什么你需要 join_table 试图理解?
  • @ArupRakshit 我是根据这里的建议进行此尝试的:stackoverflow.com/questions/29906256/… 所以也许你会发现这个问题更有帮助。最后我正在尝试使用多个模型创建一个 tag_cloud 。如果您需要,我愿意聊天。我下一小时有空:)

标签: ruby-on-rails ruby tags rails-activerecord acts-as-taggable-on


【解决方案1】:

在我看来,您可以使用 polimorphing。请看Active Record Associations

在您的情况下,模型可能是下一个:

class Tag < ActiveRecord::Base
  belongs_to :taggable, polymorphic: true 
....

class Habit < ActiveRecord::Base
  has_many :tags, as: :taggable
....

class Goal < ActiveRecord::Base
  has_many :tags, as: :taggable
....

在迁移中:

create_table :tags , force: true do |t|
  t.references :taggable, polymorphic: true, index: true
  t.timestamps null: false    
end

之后你可以:

@tags = Tag.include(:taggable)
@tags.each do |tag|
  type = tag.taggable_type # string, some of 'habit', 'goal' etc
  id = tag.taggable_id # id of 'habit', 'goal' etc
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-20
    • 2014-02-08
    • 2016-03-29
    • 1970-01-01
    • 2020-09-01
    • 2012-04-11
    相关资源
    最近更新 更多