0

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

Variety,,,Trial_Result

我有一个表格

<%= 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
4

2 回答 2

1

要实现您想要的,几乎没有什么可做的。在搜索方法中,不是获取所有参数,而是获取品种variety_1和variety_2参数,然后在数据库中查找并使用关联查找结果,然后计算差异。创建视图并显示信息。

于 2013-10-30T08:31:36.867 回答
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 %>
于 2013-10-30T19:57:52.183 回答