开发者

Ruby on Rails: One-to-many relationships, but I only want to retrieve just students and 1 homework

开发者 https://www.devze.com 2023-04-13 00:17 出处:网络
I\'ve 2 objects, Student 开发者_StackOverflow社区and Homework. This is a one-to-many relationship where a student can have many Homeworks

I've 2 objects, Student 开发者_StackOverflow社区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.


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:

Student.find(:all, :include => :homeworks).each {|student| student.homeworks.first}

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.


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)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号