我希望从我的应用中的所有用户获取ID为37的品牌的所有标签。以下内容有效,但只能从应用中当前2个用户中的一个获取标签:
<%= BrandUser.last.brand.tags.join(", ") %>
以下是我的尝试,但不起作用:
<%= BrandUser.where(:brand_id => 37).each {|brand| p brand.tags} %>
以下是我的架构:
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)
答案 0 :(得分:1)
只需选择标记taggable_id
为brand_id
,taggable_type
为Brand
,tagger_type
为User
,并包含tag
。
Tagging.where(:taggable_id => 37, :taggable_type => 'Brand', :tagger_type => 'User').include(:tag)
要执行相同操作,但仅适用于与品牌相关联的用户,以及:tagger_id字段:
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)