簡體   English   中英

搜索多個表Rails

[英]Search Multiple tables Rails

我有一個我不確定如何最好地解決的問題。 我的數據庫中有三個表,我需要從中檢索數據並進行顯示。

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

要實現您想要的目標,要做的工作還很少。 在搜索方法中,不是獲取所有參數,而是獲取品種variant_1和variant_2參數,然后在數據庫中查找並使用關聯關系查找結果,然后計算差異。 創建一個視圖並顯示信息。

如果需要以一種形式創建/更新多個對象,則建議您創建不連接數據庫的偽模型,例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM