我有一個標籤型號:的has_many通過,有條件
name:string
user_tag: boolean
private_tag: boolean
,並用一個簡單的連接表的圖像模型(picture_id,TAG_ID)
我想有picture.tags,picture.user_tags ,和picture.private_tags爲什麼下面的代碼不工作,我應該如何解決它?
has_many :tags, -> { where :private_tag => false and :user_tag => false }, through: :pictures_tags
has_many :private_tags, -> { where :private_tag => true }, through: :pictures_tags
has_many :user_tags, -> { where :user_tag => true }, through: :pictures_tags
!!編輯!
所以我得到了它不能在這裏工作:
has_many :tags, through: :pictures_tags, :source => :tag, :conditions => ['tags.private_tag = ? and tags.user_tag = ?', false, false]
has_many :private_tags, through: :pictures_tags, :source => :tag, :conditions => ['tags.private_tag = ?', true]
has_many :user_tags, through: :pictures_tags, :source => :tag, :conditions => ['tags.user_tag = ?', true]
但它似乎是回到了兩次。
2.1.1 :036 > picture = Picture.last
Picture Load (0.4ms) SELECT "pictures".* FROM "pictures" ORDER BY "pictures"."id" DESC LIMIT 1
=> #<Picture id: 378, user_id: 35, picture: "i6.JPG", created_at: "2014-11-23 12:19:35",
updated_at:"2014-11-23 12:19:35", number_of_votes: 0, number_of_upvotes: 0,
blurb: "!test @test #test">
2.1.1 :037 > picture.private_tags
Tag Load (0.2ms) SELECT "tags".* FROM "tags" INNER JOIN "pictures_tags" ON "tags"."id" = "pictures_tags"."tag_id" WHERE (tags.private_tag = 't') AND "pictures_tags"."picture_id" = ? [["picture_id", 378]]
=> #<ActiveRecord::Associations::CollectionProxy
[#<Tag id: 198, name: "!test", created_at: "2014-11-23 12:19:35", updated_at: "2014-11-23 12:19:35",
private_tag: true, user_tag: false>, #<Tag id: 198, name: "!test", created_at: "2014-11-23 12:19:35",
updated_at: "2014-11-23 12:19:35", private_tag: true, user_tag: false>]>
2.1.1 :038 > picture.private_tags.count
(0.3ms) SELECT COUNT(*) FROM "tags" INNER JOIN "pictures_tags" ON "tags"."id" = "pictures_tags"."tag_id" WHERE (tags.private_tag = 't') AND "pictures_tags"."picture_id" = ? [["picture_id", 378]]
=> 2
您正在使用哪個版本的Rails?前者(與範圍)是4.x,後者(與conitions)是3.2。 – blelump 2014-11-23 12:41:20
Im使用rails 4 – 2014-11-23 12:44:30
'pictures.pictures_tags'看起來像什麼?你看到這個表中有重複嗎? – 2014-11-23 13:46:35