的has_many通过,有条件
我有一个标签型号:的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
您可能遇到语法问题。这些协会:
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
我注意到OP关于错误的语法,他编辑问题。 – 2014-11-23 13:02:09
让我们继续使用范围,因为它是Rails 4的有效方法。 – blelump 2014-11-23 13:05:03
是的,我把'你不清楚你在问什么',因为我不明白这个问题和OP没有说错误的语法。 – 2014-11-23 13:06:17
您正在使用哪个版本的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