在 rails 上使用 ruby 查询 "where"

Query "where" with ruby on rails

我在我的应用程序中将帖子作为想法发布,这些想法属于 activity 和状态。 我想按 activity 对它们进行排序以获得一种状态,所以我在我的控制器中做了

@idees_en_place = Idee.where(statut_id= "2")
@activites = Activite.all

在我看来 :

<% @activites.each do |activite| %>
  <div class="idee en-place col-lg-5" style="background:#<%= activite.color%>">
    <h2><%= activite.name %></h2>
    <p>
     <% @idees_en_place.where(activite_id = activite.id).limit(3).each do |idee| %>
     <div class="idee">
       <h6><%= link_to idee.title, idee %></h6>
      </div>
     <% end %>
  </p>
  </div>
<% end %>

但这行不通,activity 的每个部分都没有对想法进行排序。 我认为这是一个小错误,但我不知道如何解决这个问题

控制器中

@idees_en_place = Idee.where(statut_id: 2)
@activites = Activite.all

查看

<% @activites.each do |activite| %>
  <div class="idee en-place col-lg-5" style="background:#<%= activite.color%>">
    <h2><%= activite.name %></h2>
    <p>
     <% @idees_en_place.where(activite_id: activite.id).limit(3).each do |idee| %>
     <div class="idee">
       <h6><%= link_to idee.title, idee %></h6>
      </div>
     <% end %>
  </p>
  </div>
<% end %>
@idees_en_place = Idee.where(statut_id= "2")

这段代码有两个问题。

首先,idInteger 类型(除非您已将其定义为 String)。 其次,它是您传递给 where 子句的键值,并且您将它们作为

传递
:status_id => 2 # old hashrocket syntax

status_id: 2 # new syntax

这部分也一样

@idees_en_place.where(activite_id = activite.id)

应该是

@idees_en_place.where(activite_id: activite.id)

我只想指出,您将 运行 陷入 N+1 查询问题,为避免这种情况,您应该预加载所有内容,而不是在视图中进行查询。

控制器:

#change if the association name is different
@activites = Activite.includes(:idees)

风景

<% @activites.each do |activite| %>
  <div class="idee en-place col-lg-5" style="background:#<%= activite.color%>">
    <h2><%= activite.name %></h2>
    <p>
     <% activitie.idees[0..2].each do |idee| %>
     <div class="idee">
       <h6><%= link_to idee.title, idee %></h6>
      </div>
     <% end %>
  </p>
  </div>
<% end %>

备注:

我使用了 [0..2] 格式,因为我想避免 ActiveRecord 执行新查询,另一种方法是使用类似这样的方式限制查询

@activites = Activite.includes(:idees).merge(Idee.limit(3))

然后你就不需要在视图中使用任何限制,但我还没有测试过这个,现在无法在 rails 机器上访问。

我认为以下代码会对您有所帮助:

由于您的 Idee 属于 activity 和状态,因此您的 Idee table.

中有 activity_id 和 status_id

您可以通过以下方式找到状态的所有想法:

Idee.where(:status_id => 2)

并且您可以使用 order

以 Asc 或 desc 顺序对 Idee 进行排序
idees = Idee.join(:activity).where(:status_id => 2).order(:activity_id => :asc)
idees = Idee.join(:activity).where(:status_id => 2).order(:activity_id => :desc)

<% activity_id = -1%>
<@idees.each do |idee| %>
  <div class="idee en-place col-lg-5" style="background:#<%= idee.activite.color%>">
  <h2><%= idee.activity.name %></h2>
  <p>
    <% if activity_id != idee.activity_id  %>
      <% activity_id = idee.activity.id %>
      <% counter = 0 %>
    <% end %>
    <% if counter < 3 %>
      <% counter = counter + 1%>
      <div class="idee">
        <h6><%= link_to idee.title, idee %></h6>
      </div>
    <% end %>
  </p>
</div>