鉴于这四种模式:
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
我想获得成绩册中的所有成绩单条目,包括其相关的gradebook_entry_score,但只有属于特定用户的成绩单。
这就是我现在的做法:
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} )
=> []
我希望始终获得所有gradebook_entries,无论该用户是否有gradebook_entry_score。
那么,即使附表中没有结果,我怎样才能确保从第一张表中得到结果?
编辑1:
用户可能没有特定gradebook_entry的gradebook_entry_score。
答案 0 :(得分:1)
我希望.where(:gradebook_entry_scores => {:user_id => 50} )
是你的问题。
如果您从相关用户开始,例如:
,该怎么办?User.find_by_id(50).gradebooks.gradebook_entries.includes(:gradebook_entry_scores)