ID が 37 のブランドのアプリ内のすべてのユーザーからすべてのタグを取得したいと考えています。
<%= BrandUser.last.brand.tags.join(", ") %>
以下は私の試みですが、うまくいきません:
<%= BrandUser.where(:brand_id => 37).each {|brand| p brand.tags} %>
- ブランドには has_many タグ、has_many brand_users、および brand_users による has_many ユーザー
- ユーザー has_many :brand_users および has_many :brands, :through => :brand_users
- BrandUser belongs_to :brand および belongs_to :user
以下は私のスキーマです:
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
解決策:
以下の回答に従って、コンソールで次を実行すると、探していたタグが表示されました。
ActsAsTaggableOn::Tagging.where(:taggable_id => 37, :taggable_type => 'Brand', :tagger_type => 'User').includes(:tag)
ただし、次の実行も機能します。
Brand.find(37).all_tags_on(:tags)