开发者

named_scope join aliasing issues

I have a named_scope which does a join. I have included the named_scope method below

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_th开发者_C百科an_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}%"])

I ran the above line and got an aliasing error

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

Is there any way to get around this..


somewhere you have a has_many something :through => :member_meetings that you're not showing here. I'd guess that something is attenders.

Anyway, you're joining attenders in the scope's joins and then again in the :include options, thus requiring the same tables twice.

If that's correct you should define the scope like this

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"

That joins query might look like this

: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"

Note that I aliased both member_meetings & attendees.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜