我是rails的新手,正在学习为学校完成一个库存系统数据库项目。
这是我的物品型号:
class Item < ActiveRecord::Base
self.primary_key ='item_id'
validates :item_id, :presence => true
has_one :vendor_item, :dependent => :destroy
has_one :vendor, :through => :vendor_item
accepts_nested_attributes_for :vendor_item
end
这是我的项目控制器:
class ItemsController < ApplicationController
def new
@item = Item.new
@all_vendors = Vendor.all
@item_vendor = @item.build_vendor_item
end
def create
@item = Item.new(item_params)
vendor = params[:vendors][:id]
@item_vendor = @item.build_vendor_item(:vendor_id => vendor)
@item_vendor.save
#raise params.inspect
if @item.save
redirect_to @item
else
render 'new'
end
end
def show
@item = Item.find(params[:id])
@item_vendor = @item.vendor_item
end
def index
@items = Item.all
end
def priceUnder500
@priceUnder500 = Item.where("price < ?", 500)
respond_to do |format|
format.html
format.js
end
end
def priceOver500
@priceOver500 = Item.where("price > ?", 500)
respond_to do |format|
format.html
format.js
end
end
def edit
@item = Item.find(params[:id])
@all_vendors = Vendor.all
@vendor_item = @item.vendor_item
end
def update
@item = Item.find(params[:id])
vendor = params[:vendors][:id]
if @item.vendor_item.blank?
@item.build_vendor_item(:vendor_id => vendor)
end
if @item.update(params[:item].permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id]))
redirect_to items_path
else
render 'edit'
end
end
def destroy
@item = Item.find(params[:id])
@item.destroy
redirect_to items_path
end
private
def item_params
params.require(:item).permit(:item_id, :name, :category, :description, :reorder_level, :quantity, :price, :vendor_item_attributes => [:vendor_item_id])
end
end
我的
答案 0 :(得分:0)
def create
@item = Item.new(item_params)
@vendor = params["item"]["vendors"]
if @item.save
@item.create_vendor_item(@vendor.id => vendor).save
redirect_to @item
else
render 'new'
end
end
答案 1 :(得分:0)
您尚未将结果保存在create
操作中的实例变量中。
尝试在创建操作中这样做。
def create
@item = Item.new(item_params)
vendor = params[:vendors][:id]
@item_vendor = @item.build_vendor_item(:vendor_id => vendor)
if @item.save
redirect_to @item
else
render 'new'
end
end