has_many通过,有条件

时间:2014-11-23 12:05:45

标签: ruby-on-rails

我有一个Tag模型:

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

!! EDIT !!

所以我觉得这不行:

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 

1 个答案:

答案 0 :(得分: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