我有这种愤怒的联想:融资> - 事件> - 子程序> - 程序。我希望通过所有程序从程序中访问last_financings,因此代码是:
class Fcp < Program
has_many :fcp_subprograms,
:foreign_key => 'parent_id'
has_many :subprogram_last_actual_financings,
:through => :fcp_subprograms,
:source => :last_actual_financings
class FcpSubprogram < Program
belongs_to :fcp,
:class_name => 'Fcp',
:foreign_key => 'parent_id'
has_many :events,
:foreign_key => 'fcp_id'
has_many :last_actual_financings,
:through => :events,
:source => :last_actual_financings
class Event < ActiveRecord::Base
belongs_to :fcp,
:class_name => 'Fcp',
:foreign_key => 'fcp_id'
belongs_to :fcp_subprogram,
:class_name => 'FcpSubprogram',
:foreign_key => 'fcp_id'
has_many :last_actual_financings,
:class_name => 'ActualFinancing',
:order => 'date DESC',
:limit => 1
所以,当我想在after_initialize函数中访问subprogram_last_actual_financings时,我收到此错误
Invalid source reflection macro :has_many :through for has_many :subprogram_last_actual_financings, :through => :fcp_subprograms. Use :source to specify the source reflection.
但我有:我的关联中的源选项。我做错了什么?
答案 0 :(得分:6)
你得到的错误是关于source_reflection是一个无效的关联,因为has_many的源必须是belongs_to,has_one或has_many而没有through选项。所以你不能使用:last_actual_financings作为源。
答案 1 :(得分:3)
据我记得你不能与双重(或更多)联系:通过。你唯一能做的就是编写自己的SQL查询。
以下是我的示例:
class Person
...
has_many :teams, :finder_sql =>
'SELECT DISTINCT teams.* FROM teams
INNER JOIN team_roles ON teams.id = team_roles.team_id
INNER JOIN team_members ON team_roles.id = team_members.role_id
WHERE ((team_members.person_id = #{id}))'
# other standard associations
has_many :team_members
has_many :team_roles,
:through => :team_members
# and I couldn't do:
# has_many :teams, :through => :team_roles
这是关系人物 - &gt; has_many - &gt; team_members - &gt; has_many - &gt; team_roles - &gt; has_one - team。
希望它有所帮助。
答案 2 :(得分:0)
这似乎是一种非常尴尬的做法...我宁愿在Program
中创建一个虚拟访问器来调用这样的东西:
self.subprograms.first.events.first.financings.first(:order => 'date DESC')