0

鉴于这四个模型:

class Gradebook < < ActiveRecord::Base
  has_many :gradebook_entries
end

class User < ActiveRecord::Base
  has_many :gradebook_entry_scores
end

class GradebookEntry < ActiveRecord::Base
  has_many :gradebook_entry_scores
end

class GradebookEntryScore < ActiveRecord::Base
  belongs_to :gradebook_entry
  belongs_to :user
end

我想获取成绩簿中的所有成绩簿条目,包括其关联的成绩簿条目分数,但只有属于特定用户的成绩簿条目。

这就是我现在的做法:

some_gradebook.gradebook_entries.includes(:gradebook_entry_scores).where(:gradebook_entry_scores => {:user_id => 50} )   

它有效。除非该用户没有gradebook_entry_score,否则不会返回gradebook_entry。

    some_gradebook.gradebook_entries.includes(:gradebook_entry_scores).where(:gradebook_entry_scores => {:user_id => 50} )
=> []

我想始终获得所有成绩簿条目,无论该用户是否有成绩簿条目分数。

那么,即使包含的表中没有结果,我如何确保我会从第一个表中获得结果?

编辑1:

用户可能没有特定gradebook_entry 的gradebook_entry_score。

4

1 回答 1

1

我希望这.where(:gradebook_entry_scores => {:user_id => 50} )是你的问题。

如果您从有问题的用户开始怎么办,例如:

User.find_by_id(50).gradebooks.gradebook_entries.includes(:gradebook_entry_scores)
于 2013-04-18T19:55:49.823 回答