【问题标题】:Rails, where filter on an already joined tableRails,过滤已连接的表
【发布时间】:2018-04-24 21:29:15
【问题描述】:

我有一个表 :periods 有一列 :hours

我还有一个表 :simulations 属于 :period (所以它有 period_id 作为列)

我加入2桌

@simulations=Simulation.join(:period) #Controller

现在在我看来,我必须遍历我的模拟,但要根据周期表中存在的“小时”列进行过滤。

所以我尝试了类似的东西

在我看来,我必须循环模拟:

<% @simulations.where( :period => {:hour => count})each do |sim| %>

<% @simulations.periods.where(:hour => count )each do |sim| %>

再次,我想根据周期表中的数据过滤我的模拟。这些方法都不起作用。我也尝试过使用 include 和 eager_loads,这两种方法都不起作用。

我是否正在尝试一些在 Rails 下不可能的事情?

我也在使用 postgres

【问题讨论】:

    标签: ruby-on-rails postgresql join filter include


    【解决方案1】:

    尝试在您的控制器中使用此查询

    @simulations = Simulation.where(periods: {hours: count}) # All simulations that belongs to periods with hours = count
    

    注意,'periods' 中的 's' 并根据您的列名调整 'hours' 中的 's'。

    在视图中,直接使用模拟变量:

    <%= @simulations.each do |sim| %>
    

    您对加入期和模拟进行了两次相同的查询。还要尽量避免在视图或控制器中对模型进行任何查询。相反,您应该在 Model 中创建一个方法并使用它来获取上述查询的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-21
      • 1970-01-01
      • 2015-03-26
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 2022-08-24
      • 2021-09-05
      相关资源
      最近更新 更多