2016-01-22 51 views
0

這裏子句在Ruby中polymorphics協會是我在做什麼如何使用其中on Rails的

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) 
+0

那麼問題是什麼? –

+1

它不工作,undefine表名可temable 我也試試這個 Temp.includes(:tempable).where(tempable:{text:text}) 它也不起作用 –

+1

請把問題放在題。 –

回答

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>] 

請試試吧。

+0

我該怎麼做才能做到這一點 所有評論文章標題是「標題」 Comment.includes(:commentable).where(「commentable.title =?」,「title」) –

+0

好的,嘗試添加'belongs_to:article, - >(record){where(評論:{commentable_type:「Article」})},foreign_key::commentable_id,class_name:「Article」到'Comment'模型,並且您可以執行'Comment.joins(:article).merge(Article.where('articles.title LIKE?','%xxx%'))。all'。 – yhirano55

+0

是的,我可以訪問數據,當我從文章查詢,但這也是有幫助的 –