如何从 categories:string 创建多个表?

How to Create Multiple Tables from a categories:string?

我正在尝试创建下面的两个表格。当用户提交 _form 时,他会勾选 "Average" 或 "Instance." 如何使用 Associations or Query interface 从较大的量化支架创建这两个分类表?

Rails g scaffold Quantified categories:string name:string metric:string result:decimal date:date

任何方向将不胜感激。我只是对我应该寻找的东西感到不知所措。

quantifieds_controller.rb

class QuantifiedsController < ApplicationController
  before_action :set_quantified, only: [:show, :edit, :update, :destroy]
  before_action :authenticate_user!, except: [:index, :show]

  def index
   @quantifieds = Quantified.all.order("date")
   @average_quantifieds = current_user.quantifieds.average
   @instance_quantifieds = current_user.quantifieds.instance
  end

  def show
  end

  def new
    @quantified = current_user.quantifieds.build
  end

  def edit
  end

  def create
    @quantified = current_user.quantifieds.build(quantified_params)
    if @quantified.save
      redirect_to quantifieds_url, notice: 'Goal was successfully created'
    else
      render action: 'new'
  end
end

  def update
    if @quantified.update(quantified_params)
      redirect_to quantifieds_url, notice: 'Goal was successfully updated'
    else
      render action: 'edit'
  end
end

  def destroy
    @quantified.destroy
    redirect_to quantifieds_url
  end

  private
    def set_quantified
      @quantified = Quantified.find(params[:id])
    end

    def correct_user
      @quantified = current_user.quantifieds.find_by(id: params[:id])
      redirect_to quantifieds_path, notice: "Not authorized to edit this goal" if @quantified.nil?
    end

    def quantified_params
      params.require(:quantified).permit(:categories, :name, :metric, :result, :date)
    end
end

quantified.rb

class Quantified < ActiveRecord::Base
    belongs_to :user

    CATEGORIES = ['Monthly Average', 'One-Time Instance']
end

索引

<table>
    <% @average_quantifieds.each do |average| %>
      ....
    <% end %>
</table>

<table>
    <% @instance_quantifieds.each do |instance| %>
        ....
    <% end %>
</table>

user.rb

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

    has_many :goals
    has_many :values
    has_many :quantifieds
end

在 rb 文件中:

class Quantified < ActiveRecord::Base
 belongs_to :user
  scope :averaged,  -> { where(categories: 'Monthly Average') }
  scope :instance, -> { where(categories: 'One-Time Instance') }

 CATEGORIES = ['Monthly Average', 'One-Time Instance']
end

我将所有内容从 "average" 更改为 "averaged",否则我会收到一条错误消息。