2014-11-23 81 views
1

我有一個標籤型號:的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 
+0

您正在使用哪個版本的Rails?前者(與範圍)是4.x,後者(與conitions)是3.2。 – blelump 2014-11-23 12:41:20

+0

Im使用rails 4 – 2014-11-23 12:44:30

+0

'pictures.pictures_tags'看起來像什麼?你看到這個表中有重複嗎? – 2014-11-23 13:46:35

回答

1

您可能遇到語法問題。這些協會:

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, -> { where :private_tag => false and :user_tag => false }, through: :pictures_tags 

因爲where條款並不需要一個條件作爲參數(它不是一個有效的條件要麼),但Hash。所以它會是:

has_many :tags, -> { where :private_tag => false, :user_tag => false }, through: :pictures_tags 
+0

我注意到OP關於錯誤的語法,他編輯問題。 – 2014-11-23 13:02:09

+0

讓我們繼續使用範圍,因爲它是Rails 4的有效方法。 – blelump 2014-11-23 13:05:03

+0

是的,我把'你不清楚你在問什麼',因爲我不明白這個問題和OP沒有說錯誤的語法。 – 2014-11-23 13:06:17