我的应用程序有用户、植物和工厂帖子。以下是我的联想
class User
has_many: plants
has_many :plantposts, through: :plantposts
end
class Plant
has_many: plant_posts
belongs_to : user
end我有一个活跃植物的列表,我想要显示这些植物的最新(3最大)植物帖子,而不必对每个植物进行数据库调用。
我认为使用一个带有所有活动植物的in的对plantpost表的调用,并将结果放入散列中,然后使用结果来构建我的网页,这是一个好主意。
我不确定这是否是解决这个问题的最好方法,或者确切地说,首先如何构造对plantpost表的调用,或者在第二个位置获得最终结果以显示在正确的位置。
发布于 2015-01-21 15:29:19
我不确定您是否犯了复制错误,或者您在实际代码中是否犯了这个错误,但您的类/模型定义对我来说有点陌生。
你是不是想让他们变成这样:
class User
has_many: :plant_posts
has_many: :plants
end
class PlantPosts
belongs_to: :user
belongs_to: :plant
end
class Plant
has_many: :plant_posts
belongs_to: :user
end注意:我没有写任何presence验证,因为我仍然有点不确定你的规则是什么。
从本质上讲,这是在说,有些用户可以拥有植物。用户也可以为某一种植物制造plant_posts,但该植物不一定是他们的。
无论如何,假设您有一个包含Plant数组的active_plants方法:
# Query plant posts, ordered by mostly recently created, that are
# for active_plants and return the top 3
PlantPost.order(created_at: :desc).joins(:plants)
.where("plant_id = ?", [active_plants]).limit(3)https://stackoverflow.com/questions/28060320
复制相似问题