【发布时间】:2015-04-27 21:37:55
【问题描述】:
我有一个使用 Sequel ORM 的 Sinatra 应用程序,我试图在其中仅列出包含一个或多个帖子的类别。
所以,如果我在数据库中有两个类别; “Apples”和“Oranges”,以及一个分配给“Apples”的帖子,那么当我列出当前类别时,我只想提供“Apples”类别。
在费了很多力气之后,我终于设法让它与以下内容一起工作;
class Post < Sequel::Model
many_to_one :category
end
class Category < Sequel::Model
one_to_many :posts
dataset_module do
def with_posts
where(id: Post.select(:category_id))
end
end
end
@categories = Category.with_posts
如果在 Sequel 中有更好的方法,请告诉我。
【问题讨论】:
-
你所拥有的可能是最好的方法。
-
太好了,谢谢杰里米。