2011-08-25 84 views
2

我有一个名为_scope它进行连接。我已经包含下面named_scope加入别名问题

named_scope :has_more_than_one,{ 
      :select  => "sessions.*", 
      :joins  => :attenders, 
      :conditions => {:attenders => {:attending => true}}, 
      :group  => "sessions.id", 
      :having  => "count(sessions.id) > 1" 


Meeting.has_more_than_one.all(:group => "sessions.id", 
    :include => [:attenders => [ :issues ]], 
    :conditions => ["sessions.id in (select attenders.session_id from attenders where person_id in (select persons.id from persons where first_name like (?) or last_name like (?) or first_name like (?) or last_name like (?)))", 
     "#{attendee_first_name}%","#{attendee_last_name}%","#{attendee_last_name}%","#{attendee_first_name}%"]) 

我跑上面的一致named_scope方法,得到了一个混叠误差

ActiveRecord::StatementInvalid: Mysql::Error: Not unique table/alias: 'member_meetings' 

有什么办法来解决这个问题..

回答

2

某处你有一个的has_many东西:通过=>:member_meetings,你不显示在这里。 我想那是一些参加者。

无论如何,您正在加入作用域的连接,然后再次加入:include选项,因此需要两次相同的表。

如果这是正确的,你应该这样定义

named_scope :has_more_than_one,{ 
     :select  => "sessions.*", 
     :joins  => <specify the join with the condition here aliasing the tables>, 
     # this line would go away :conditions => {:attenders => {:attending => true}}, 
     :group  => "sessions.id", 
     :having  => "count(sessions.id) > 1" 

这联接查询可能是这样的

:joins => "inner join member_meetings mm ON mm.meeting_id = meetings.id 
      inner join attendees at ON mm.attendee_id = at.id AND 
      at.attending is true" 

注意,我既别名member_meetings &与会者范围。