【问题标题】:Polymorphic assosciation question多态关联问题
【发布时间】:2010-08-17 21:15:26
【问题描述】:

在我的 Rails 应用程序中,我的模型看起来像这样:

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :blog
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

我现在遇到的问题是在特定博客下查找所有 cmets。谁能看到这个问题的解决方案?

最好的问候, 埃里克

【问题讨论】:

  • 您是如何尝试查找 cmets 的?您可以为我们发布该代码吗?如果您在控制台中收到错误消息,错误消息是什么?
  • 我不明白你为什么要使用多态关联?
  • 您好!我正在使用多态关联,因为将来我希望允许对帖子以外的其他对象发表评论……

标签: ruby-on-rails ruby-on-rails-3 polymorphism


【解决方案1】:

你好,首先连接

class Blog < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  belongs_to :blog
  has_many :comments, :as=>:commentable #Post.first.comments or Blog.posts.first.comments
end

class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

获取所有cmets

comments=[]
Blog.first.posts.each do |post|
  comments = comments | post.comments
end

【讨论】:

  • 谢谢,我知道这个解决方案。但问题是它需要我先获取所有帖子,然后再遍历它们。我宁愿找到一种可以通过 SQL 获取它们的方法……
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-08
  • 1970-01-01
相关资源
最近更新 更多