Не удалось найти товар без идентификатора - PullRequest
0 голосов
/ 05 августа 2020

На самом деле у меня есть модель Bid с внешними ключами Product_id и User_id, я успешно назначил user_id с помощью функции current_user, но мне не удалось назначить текущий Product_id, который открывался на моей странице выставки продуктов. И, нажав кнопку ставки, я go для ставок / нового пути, где мне просто нужно ввести сумму, но после того, как я получу эту ошибку.

ActiveRecord :: RecordNotFound (Не удалось найти продукт без идентификатор):

BidController

class BidsController < ApplicationController
  before_action :set_bid, only: [:show, :edit, :update, :destroy]


  
  def index
    @bids = Bid.all
  end

  
  def show
  end

  
  def new
    @bid = Bid.new
  end


  def edit
  end

  
  def create
    @bid = Bid.new(bid_params)
    @bid.user = current_user
    @product = Product.find(params[:product_id])
    @bid.product = @product




    respond_to do |format|
      if @bid.save
        format.html { redirect_to @bid, notice: 'Bid was successfully created.' }
        format.json { render :show, status: :created, location: @bid }
      else
        format.html { render :new }
        format.json { render json: @bid.errors, status: :unprocessable_entity }
      end
    end
  end

 
  def update
    respond_to do |format|
      if @bid.update(bid_params)
        format.html { redirect_to @bid, notice: 'Bid was successfully updated.' }
        format.json { render :show, status: :ok, location: @bid }
      else
        format.html { render :edit }
        format.json { render json: @bid.errors, status: :unprocessable_entity }
      end
    end
  end

  
  def destroy
    @bid.destroy
    respond_to do |format|
      format.html { redirect_to bids_url, notice: 'Bid was successfully destroyed.' }
      format.json { head :no_content }
    end
  end

  private
    
    def set_bid
      @bid = Bid.find(params[:id])
    end

    
    def bid_params
      params.require(:bid).permit(:bidamount, :user_id, :product_id)
    end


end

Вот моя ссылка Откуда я беру Product_id

<%=link_to "Bid on this Project",new_bid_path(product_id: @product), class: "btn btn-xs btn-success" %>

routes.rb

Rails.application.routes.draw do
  resources :bids
resources :favorite_products, only: [:create, :destroy,:index]
resources :categories
resources :products
resources :users

root 'pages#home'

get 'login',  to: 'sessions#new'
get 'login',  to: 'sessions#new'
post 'login',  to: 'sessions#create'
delete 'logout', to: 'sessions#destroy'
  # For details on the DSL available within this file, see https://guides.rubyonrails.org/routing.html
end

Я обновлю свой код, если вы найдете его, чтобы узнать больше.

1 Ответ

0 голосов
/ 06 августа 2020

Вы должны создать ссылку, указав product_id link_to new_bid_path(product_id: item.id)

Затем в BidController вы должны определить новый метод

def new
  @bid = Bid.new(product_id: params[:product_id])
end

Наконец, в действии create вам не нужно не назначаем продукт, потому что он уже установлен в bid_params

Примечание: чтобы не настраивать пользователя так, как вы делаете сейчас. Попробуйте что-нибудь вроде @bid = current_user.bids.create!(bid_params). Это более короткий способ сделать то же самое

...