How can I display all tags from all users for a model instance?

▼魔方 西西 提交于 2019-12-25 08:39:38

问题


I want to get all the tags from all the users in my app for a brand whose ID is 37. The following works but only gets the tags from one of the 2 users currently in the app:

<%= BrandUser.last.brand.tags.join(", ") %>

The following is my attempt but doesn't work:

<%= BrandUser.where(:brand_id => 37).each {|brand| p brand.tags} %>
  • Brand has_many tags, has_many brand_users and has_many users through brand_users
  • User has_many :brand_users and has_many :brands, :through => :brand_users
  • BrandUser belongs_to :brand and belongs_to :user

Below is my schema:

ActiveRecord::Schema.define(:version => 20110824083919) do

  create_table "brand_users", :force => true do |t|
    t.integer  "brand_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "brands", :force => true do |t|
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "user_id"
  end

  create_table "taggings", :force => true do |t|
    t.integer  "tag_id"
    t.integer  "taggable_id"
    t.string   "taggable_type"
    t.integer  "tagger_id"
    t.string   "tagger_type"
    t.string   "context"
    t.datetime "created_at"
  end

  add_index "taggings", ["tag_id"], :name => "index_taggings_on_tag_id"
  add_index "taggings", ["taggable_id", "taggable_type", "context"], :name => "index_taggings_on_taggable_id_and_taggable_type_and_context"

  create_table "tags", :force => true do |t|
    t.string "name"
  end

  create_table "users", :force => true do |t|
    t.string   "provider"
    t.string   "uid"
    t.string   "name"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

end

Solution:

As per the answer below, running the following in the console gave me the tags I was looking for:

ActsAsTaggableOn::Tagging.where(:taggable_id => 37, :taggable_type => 'Brand', :tagger_type => 'User').includes(:tag)

However running the following also works:

Brand.find(37).all_tags_on(:tags)

回答1:


Just select the tagging where the taggable_id is the brand_id, the taggable_type is Brand, the tagger_type is User, and include tag.

Tagging.where(:taggable_id => 37, :taggable_type => 'Brand', :tagger_type => 'User').include(:tag)

To do the same but only for users that are associated with the brand, and a :tagger_id field:

Tagging.where(:taggable_id => 37, :taggable_type => 'Brand', :tagger_type => 'User', :tagger_id => User.where('brands.id' => 37).joins(:brands).select('users.id')).include(:tag)


来源:https://stackoverflow.com/questions/7273768/how-can-i-display-all-tags-from-all-users-for-a-model-instance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!