How can I display all tags from all users for a mo

2019-09-08 06:27发布

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条回答
唯我独甜
2楼-- · 2019-09-08 07:03

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)
查看更多
登录 后发表回答