我试图创建下面的两个表。当用户提交_form时,他将要么已经检查过" Average"或"实例。"如何使用Associations或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
答案 0 :(得分:0)
在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
我将所有内容从“平均”更改为“平均”,因为我收到了错误消息。