rails join的使用

假设我们的数据库中有两个表:enterprisesdaily_statistics,其中enterprises表中存储了所有企业的信息,包括企业名称和企业分类,daily_statistics表记录了所有企业的物资日统计数据,包括企业ID、日期和统计数据。

我们需要在物资日统计列表页面,根据重点商超的企业名称查询所有的物资日统计表数据。以下是一个可能的实现方式:

1. 首先,在路由文件中定义物资日统计列表的路由:

# config/routes.rb
get 'daily_statistics', to: 'daily_statistics#index'

2. 在控制器中实现index方法,查询符合条件的物资日统计数据:

# app/controllers/daily_statistics_controller.rb
class DailyStatisticsController < ApplicationController
  def index
    if params[:enterprise_name]
      # 如果参数中有企业名称,按照名称筛选
      @daily_statistics = DailyStatistic.joins(:enterprise)
                                         .where('enterprises.enterprise_type = ? and enterprises.name = ?', '重点商超', params[:enterprise_name])
      # 这里假设重点商超企业分类的名称为“重点商超”,使用joins方法连接两个表,使用where方法过滤查询条件
      # 如果使用了scope,可以将上面的查询语句封装在scope中
    else
      # 如果没有参数,查询所有物资日统计数据
      @daily_statistics = DailyStatistic.all
    end
  end
end

3. 在视图页面中,展示物资日统计数据的列表和查询表单:

# app/views/daily_statistics/index.html.erb
<%= form_tag daily_statistics_path, method: :get do %>
  <%= text_field_tag :enterprise_name, params[:enterprise_name], placeholder: '企业名称' %>
  <%= submit_tag '查询' %>
<% end %>

<table>
  <thead>
    <tr>
      <th>企业名称</th>
      <th>日期</th>
      <th>统计数据</th>
    </tr>
  </thead>
  <tbody>
    <% @daily_statistics.each do |statistic| %>
      <tr>
        <td><%= statistic.enterprise.name %></td>
        <td><%= statistic.date %></td>
        <td><%= statistic.data %></td>
      </tr>
    <% end %>
  </tbody>
</table>

在上面的代码中,我们使用form_tag方法生成一个查询表单,使用text_field_tag方法生成一个文本输入框,用于输入企业名称。在表格中展示查询结果,使用statistic.enterprise.name取出每条记录对应的企业名称。

猜你喜欢

转载自blog.csdn.net/Toml_/article/details/131220642
今日推荐