首页 > 解决方案 > Rails - Couldn't find Variant without an ID

问题描述

I am facing this error Couldn't find Variant without an ID

I don't get what is wrong :(

Stock belongs_to :variant

Variant has_many :stocks and belongs_to :product

Product

has_many :variants, inverse_of: :product, dependent: :destroy
    has_many :stocks, through: :variants

    accepts_nested_attributes_for :variants

stock.html.erb

<%= simple_form_for(Stock.new, url: admin_stocks_path) do |f| %>
    <%= f.select :variant_id, options_from_collection_for_select(@product.variants, :id, :size),required: true %>
    <%= f.input :quantity, required: true %>
   <%= f.submit %>
<% end %>

stocks_controller.rb

 class StocksController < ApplicationController

    def show
        @stock = Stock.find(params[:id])
    end

    def index
        @stocks = Stock.all
        @variants = Variant.all
    end

    def new 
        @stock = Stock.new
        @product = Product.find(params[:product_id])
        @variants = @product.variants
    end

    def create
        find_variant
        @product = @variant.product
        @stock = Stock.new(stock_params)
        if @stock.save
            redirect_to  stock_product_path(@product)
        else
            redirect_to stock_product_path(@product), alert: "Woops"
        end
    end

    private

    def stock_params
        params.require(:stock).permit(:id, :quantity, :variant_id )
    end

    def find_variant
        @variant = Variant.find(params[:variant_id])
    end
end

I did fake the find_variantmethod with Variant.find(2) and it was working... Why I can't find the :variant_id?

here is my table stocks from my schema.rb

 create_table "stocks", force: :cascade do |t|
    t.integer "quantity"
    t.bigint "variant_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["variant_id"], name: "index_stocks_on_variant_id"
  end

标签: ruby-on-rails

解决方案


params[:variant_id] will not be the value. You meant stock_params[:variant_id]


推荐阅读