Ant*_*com 7 ruby tags ruby-on-rails acts-as-taggable-on rails-activerecord
我有一个联接表
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
Run Code Online (Sandbox Code Playgroud)
其目的是使tag_cloud适用于多个模型.我把它放在application_controller中
def tag_cloud
@tags = CombineTag.tag_counts_on(:tags)
end
Run Code Online (Sandbox Code Playgroud)
我的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 %>
Run Code Online (Sandbox Code Playgroud)
我在所有模型的_form中都有这一行:<%= f.text_field :tag_list %>
combine_tags_helper
module CombineTagsHelper
include ActsAsTaggableOn::TagsHelper
end
Run Code Online (Sandbox Code Playgroud)
楷模
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
Run Code Online (Sandbox Code Playgroud)
如果您需要进一步的解释或代码来帮助我,请告诉我:)
在我看来,你可以使用多态性。请参阅活动记录关联
在你的情况下,模型可能是下一个:
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
....
Run Code Online (Sandbox Code Playgroud)
在迁移中:
create_table :tags , force: true do |t|
t.references :taggable, polymorphic: true, index: true
t.timestamps null: false
end
Run Code Online (Sandbox Code Playgroud)
之后您可以:
@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
Run Code Online (Sandbox Code Playgroud)