左外连接不会带来预期的结果

时间:2014-02-11 05:46:40

标签: ruby-on-rails-4 left-join

假设我有以下3种型号:

class User < ActiveRecord::Base
   has_many :subscriptions
   has_many :newsletters, through: :subscriptions
end

class Newsletter < ActiveRecord::Base
   has_many :subscriptions
   has_many :users, through: :subscriptions
end

class Subscription < ActiveRecord::Base
   belongs_to :user
   belongs_to :newsletter
end

我创建了2个用户:Alice和Bob,以及3个简报(标题1,标题2和标题3) Alice在HTML中订阅了“标题1”,Bob在纯文本中订阅了“标题3”

对于用户的节目动作,我想呈现所有可用新闻简报的表格,如果用户订阅了任何 - 显示相关信息:

User name: Alice

Subscriptions:
------------------- 
|Newsletter|Format|
------------------- 
| title 1  |Html  |
------------------- 
| title 2  |<NONE>|
------------------- 
| title 3  |<NONE>|
------------------- 

但我得到的是这张桌子:

------------------- 
|Newsletter|Format|
------------------- 
| title 1  |Html  |
------------------- 
| title 2  |<NONE>|
------------------- 
| title 3  |Text  |  <--- this is coming from Bob's record
------------------- 

以下是我如何提取数据:

def show
  @subs = Newsletter.joins("LEFT OUTER JOIN subscriptions ON  
      subscriptions.newsletter_id = newsletters.id and   
      subscriptions.user_id = #{@user.id}").includes(:subscriptions)
end

上面的查询转向了以下SQL:

Newsletter Load (0.3ms)    
SELECT "newsletters".* FROM "newsletters"   
LEFT OUTER JOIN subscriptions 
ON subscriptions.newsletter_id = newsletters.id and subscriptions.user_id = 1

Subscription Load (0.2ms)  
SELECT "subscriptions".* FROM "subscriptions" 
WHERE "subscriptions"."newsletter_id" IN (1, 2, 3)

我尝试在查询结尾添加.where(:user_id == @user.id),但结果是一样的。

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我找到了解决方法......

我正在提取数据并手动构建一个数组以传递给视图:

  def show
    @subs =[]

    Newsletter.all.each do |nl|
    @subs << {:newsletter => nl, :subscription =>  
                  @user.subscriptions.to_a.detect{|s| s.newsletter_id==nl.id}}

    end
  end

然后在视图中我迭代该数组并可以访问模型:

<ul>
    <% @subs.each do |s| %>
         <li>
             <%= s[:newsletter].title %> - ( 
               <%= if s[:subscription] 
                 s[:subscription].format 
               else
                 'NONE'
               end %> )
         </li>
   <% end %>
</ul>

如果某人有更好的解决方案,我很乐意知道

相关问题