搜索多个表Rails

时间:2013-10-30 01:42:57

标签: ruby-on-rails ruby-on-rails-3

我有一些问题,我不确定如何最好地接近。我的数据库中有三个表需要从中检索和显示数据。

表格VarietyTrialResult

我有一个表单

<%= simple_form_for :search, url: vpc_search_path do |f| %>
    <%= f.input :variety_one, collection: @variety, :include_blank => false %>
    <%= f.input :variety_two, collection: @variety, :include_blank => false %>
    <%= f.input :irrigations, 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').pluck(:variety_id)
    @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
    @search = params[:search]
  end
end

我的模型

class Vpc < ActiveRecord::Base
  has_many :varieties
  has_many :results
  has_many :trials
end

我需要的是一旦搜索表单完成,它会在表格中显示结果:

Variety One |  Variety Two  | Difference

2 个答案:

答案 0 :(得分:1)

要实现你想要的东西,还有很多工作要做。在搜索方法中,不是获取所有参数,获取品种variety_1和variety_2参数,然后在数据库中找到并使用关联来查找结果,然后计算差异。创建视图并显示信息。

答案 1 :(得分:0)

如果您需要在一个表单中创建/更新多个对象,那么我建议您在不连接数据库的情况下创建伪模型,例如:

class Node
  include ActiveModel::Validations
  include ActiveModel::Conversion
  extend ActiveModel::Naming

  attr_accessor :name, :content, :variety, :region, :etc

  def initialize(attributes = {})
    attributes.each do |name, value|
      send("#{name}=", value)
    end
  end

  def persisted?
    false
  end

  def save
    # here you do save of your data to distinct models
    # for example
    named_model = NamedModel.create! name: name, variety: variety
    details = Details.create! region: region, etc: etc
    content_holder = ContentHolder.create! content: content, named_id: named_model.id, details_id: details.id
  end

end

并像普通活动模型一样使用它:

<%= form_for @node do |f| %>
  <% f.text_field :name %>
  <% f.text_area :content %>
  <% f.text_field :variety %>
  <% f.text_field :region %>
  <% f.text_area :etc %>
  <% f.submit %>
<% end %>