named_scope连接别名问题

时间:2011-08-25 07:06:12

标签: ruby-on-rails activerecord

我有一个进行连接的named_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}%"])

我运行了上面一行并出现了别名错误

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

有没有办法解决这个问题..

1 个答案:

答案 0 :(得分:2)

在某个地方,你有一个has_many的东西:through => :您未在此处显示的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和amp;与会者。