我有两个表事件和作业
events assignments
===== ============
sport_id sport_id
home_school_id school_id
name division_id
我正在尝试选择事件并加入分配,如下所示:
joins = "LEFT JOIN assignments sa on events.sport_id = sa.sport_id
AND events.home_school_id = sa.school_id"
events = Event.find(:all, :joins => joins)
问题是这不会返回除法_id。为什么不 ?是因为没有关联吗?
我不应该events.first.division_id
吗?我在mysql中试过这个并且它工作正常。
我的活动模特协会
has_many :assignments,
:primary_key => :sport_id,
:foreign_key => :sport_id,
:finder_sql =>
'SELECT sa.* ' +
'FROM events e, assignments sa ' +
'WHERE e.sport_id = sa.sport_id AND e.home_school_id = sa.school_id ' +
'ORDER BY e.event_date'
答案 0 :(得分:3)
你应该尝试:
events = Event.find(:all, :include => [:assignments])
然后进入内部部门:
events.first.assignment.division_id
这假设你讲的是has_many:assignments
的事件答案 1 :(得分:0)
我最终使用了composite_primary_keys
gem:
https://github.com/drnic/composite_primary_keys
这允许您拥有多个外键。之后我只做了一个包括(像GrantG的回答)。最后,我使用rails'group by function将另一个表中的数据转换为哈希:
divisions_hash = events.group_by{|item| item.assignment.division_id}
至于我现在可以告诉我最初想要做什么(在每个记录的活动记录结果中加入其他表属性)是不可能的。