左外连接,具有Active Record上的条件

时间:2014-11-06 06:09:24

标签: mysql ruby-on-rails activerecord

如何使用条件执行左外部查询。正如我所读,ActiveRecord不允许制作我想要的东西。我试试这个:

Platform.where(url: urls).includes(:campaign_platforms).where.not('campaign_platforms.campaign_id = ?', campaign.id)

并在'where子句'中获取“Mysql2 ::错误:未知列'campaign_id'......”

UPD:

 class Platform < ActiveRecord::Base
   has_many :campaign_platforms
   has_many :campaigns, through: :campaign_platforms
   has_many :posts
   has_many :screenshoots
   belongs_to :platform_category
   belongs_to :user
 end


 class CampaignPlatforms < ActiveRecord::Base
    belongs_to :campaign, dependent: :destroy
    belongs_to :platform, dependent: :destroy
 end


 class Campaign < ActiveRecord::Base
    has_many :campaign_platforms
    has_many :platforms, through: :campaign_platforms
 end

3 个答案:

答案 0 :(得分:3)

ActiveRecord使您能够在JOIN方法中指定joins条件。

Platform.joins('JOIN campaign_platforms ON platforms.id = campaign_platforms.platform_id JOIN campaigns ON campaigns.id = campaign_platforms.campaign_id').where('campaign_platforms.campaign_id <> ? AND url IN ?', campaign.id, urls)

这意味着您可以将JOIN更改为LEFT JOINLEFT OUTER JOIN或任何您想要的内容。

大多数人倾向于使用疯狂的解决方法来避免编写单个SQL片段。不要害怕。 ActiveRecord不是要完全替换SQL。

答案 1 :(得分:1)

也许您可以使用Ob_start()

Ob_flush();

我尝试了eager_load,但它抛出了一个未定义的方法错误。

如果您希望显示没有广告系列平台的所有广告系列,它就像魅力一样。

答案 2 :(得分:0)

Soluction

#controller
@search = Box.distinct.select('boxes.*, people.first_name, people.last_name').includes(:street, :block).order('boxes.created_at DESC')
                  .left_outer_joins(orders: [{user: :people}])
                  .page(params[:page]).ransack(params[:q])
 @boxes = @search.result

#view
<% @boxes.each do |box| %>
<tr>
   <td><%= box.number %><%=box.first_name %><%=box.last_name %></td>
</tr>
<% end %>