我在我的 rails 应用程序中搜索多个表时遇到了一些问题,我不确定解决这个问题的最佳方法。
我有两个表:试用(has_many :results)和结果(belongs_to :trial)。我想创建一个点击这两个表并获取相关结果的搜索表单。
我想根据年份、灌溉(0、1、2 整数)和地区比较“variety_one”和“variety_two”中的数据,并在 3 列表中列出。第一列是“品种一”,第二列是“品种二”,第三列是前两者之间的差异。IE
结果有列:variety_id(与 :variety_one 和 :variety_two 参数有关),试验年有列:region_id, irrigated
| Variety One | Variety Two | Different
Yield | 5.00 | 4.00 | 1.00
length | 1.00 | 0.50 | 0.50
我的观点
<%= simple_form_for :search, url: vpc_search_path do |f| %>
<%= f.select :variety_one, @variety.collect {|v| [v.variety_name, v.variety_id]}, :selected => '2300', :include_blank => false %>
<%= f.select :variety_two, @variety.collect {|v| [v.variety_name, v.variety_id]}, :selected => '2308', :include_blank => false %>
<%= f.input :irrigated, collection: @irrigations, as: :check_boxes, :input_html => {:checked => true} %>
<%= f.input :years, collection: @years, as: :check_boxes, :input_html => {:checked => true} %>
<%= f.input :regions, collection: @regions, as: :check_boxes, :input_html => {:checked => true} %>
<%= f.button :submit %>
<% end %>
我的控制器
class VpcController < ApplicationController
def index
all = Result.select(:variety_id)
@variety = Variety.where(:variety_id => all).order('variety_name DESC')
@years = Result.select('DISTINCT year').pluck(:year)
@regions = Trial.select('DISTINCT region_id').pluck(:region_id)
@irrigations = Trial.select('DISTINCT irrigated').pluck(:irrigated)
end
def search
@result = Result.search(params[:search])
@trial = Trial.search(params[:search])
end
end
搜索视图
<table class="table">
<th></th>
<th>Variety One</th>
<th>Variety Two</th>
<th>Difference</th>
<tr>
<td>Yield (bales/ha)</td>
<% @result.each do |v| %>
<td><%= "%.2f" % (v.lint) %></td>
<td><%= v.length %></td>
<td><%= ?? %></td>
<td></td>
<td></td>
<% end %>
</tr>
</table>