如何在Ruby on Rails中使用where子句进行多态关联

时间:2016-01-22 10:31:24

标签: ruby-on-rails ruby ruby-on-rails-4 activerecord

这就是我正在做的事情

class Temp < ActiveRecord::Base
 belongs_to :tempable,polymorphic: true
end
class TempAgain < ActiveRecord::Base
 has_many :temps  , as: :temable
end

Temp.includes(:tempable).where("{temable.table_name}.text = ?",value)

1 个答案:

答案 0 :(得分:0)

我认为您需要了解polymorphic association。这是一个例子。

型号:

class Comment < ActiveRecord::Base
  belongs_to :commentable, polymorphic: true
  belongs_to :article, ->(record) { where(comments: { commentable_type: "Article" }) }, foreign_key: :commentable_id, class_name: "Article"
end

class Article < ActiveRecord::Base
  has_many :comments, as: :commentable
end

撬:

[0] pry(main)> article = Article.create(title: 'xxx', content: 'xxx')
[1] pry(main)> 5.times.map { article.comments.build(content: 'xxx').save }
[2] pry(main)> Article.includes(:comments).find(1).comments
  Article Load (0.2ms)  SELECT  "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1  [["id", 1]]
  Comment Load (0.2ms)  SELECT "comments".* FROM "comments" WHERE "comments"."commentable_type" = 'Article' AND "comments"."commentable_id" IN (1)
=> [#<Comment:0x007fa0e22fff50
  id: 1,
  content: "comment_0",
  commentable_id: 1,
  commentable_type: "Article",
  created_at: Fri, 22 Jan 2016 10:55:02 UTC +00:00,
  updated_at: Fri, 22 Jan 2016 10:55:02 UTC +00:00>]
[3] pry(main)> Comment.joins(:article).merge(Article.where('articles.title LIKE ?', '%xxx%')).all
=> [#<Comment:0x007fc8b2be87a0
  id: 1,
  content: "comment_0",
  commentable_id: 1,
  commentable_type: "Article",
  created_at: Fri, 22 Jan 2016 10:55:02 UTC +00:00,
  updated_at: Fri, 22 Jan 2016 10:55:02 UTC +00:00>]

拜托,试试吧。