Ruby on Rails:一对多关系,但我只想检索学生和 1 个作业
我有 2 个对象,学生和家庭作业。这是一种一对多的关系,学生可以有很多作业。
我正在尝试使用 .find 方法来检索所有学生和他有的一项作业。
我知道我可以使用 Student.find(:all, :include => :homeworks)。但是,这会将学生及其所有作业归还给我。
I've 2 objects, Student and Homework. This is a one-to-many relationship where a student can have many Homeworks
I'm trying to use a .find method to retrieve all students and just one homework that he has.
I know I can use Student.find(:all, :include => :homeworks). But, this will return me the student and all it's homeworks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
如果您的关系是一对多,则您不能只选择一个而不决定应该是哪一个(例如,如果您按 id 排序,则选择第一个)。如果是这样,您可以在关系上使用
#first
方法:如果您的意思是从数据库中为每个学生只提取一个科目,则更多的是 SQL 问题。您必须编写“ON”子句,根据您的标准选择单个主题。
If your relation is one-to-many, you can't pick just one without deciding which one should it be (e.g. first one, if you order them by ids). If so, you can use
#first
method on relation:If you mean pulling only one subject for each student from database it is more of SQL problem. You would have to write 'ON' clause that would pick single subject on your criterion.
如果您不关心性能,那么您的解决方案就可以。
获取所有记录并仅使用视图或控制器中的第一个记录
如果您确实关心性能(获取大量对象的成本很高),那么您可以添加另一个关系first_homework或latest_homework(在表的架构中添加一个新列latest_homework_id)并每次为学生分配新作业(或完成作业或每当对您的应用程序逻辑有意义时)都用正确的 ID 填充它
If you don't care about performance then your solution is ok.
Fetch all record and just use the first one in your views or controllers
If you do care about performance (fetching a lot of objects is expensive) then you can add another relation first_homework or latest_homework (adding a new column latest_homework_id in your table's schema) and populate it with the correct id every time a student is assigned a new homework (or a homework is completed or whenever it makes sense for your application logic)