0
基本的に私は製品に含めるべき注文書式を実装しようとしています#表示ビューに属していないビューですOrderController。Rails - Rails 5の同じコントローラに属していないビューから作成する方法
PS:オーダーと製品モデル間appropirate関連が多対多のですが、順番はこれまでのところ、私は次のように記述している唯一の製品
が含まれているとして、私の場合、それは1対多です。 注文モデル
class Order < ApplicationRecord
belongs_to :product
belongs_to :user
end
製品モデル
class Product < ApplicationRecord
has_many :orders
has_many :comments
# define scope for fetching products that have images
scope :products_with_images, -> {where.not(image_url: nil)}
scope :products_with_comments, -> {joins(:comments).order(created_at: :desc)}
end
注文コントローラー
class OrdersController < ApplicationController
before_action :authenticate_user!
load_and_authorize_resource
def index
@orders = Order.includes(:product, :user).where(user_id: current_user.id).all
end
def new
end
def show
@order = Order.find(params[:id])
end
def create
@product = Product.find(params[:product_id])
@order = @product.order.new(order_params)
@order.user = current_user
if @order.save
redirect_to order_path(@order)
else
flash[:error] = "Something went wrong!"
end
end
def destroy
end
private
def order_params
params.require(:order).permit(:user_id, :total)
end
end
プロダクトコントローラー
def show
@comments = @product.comments.order("created_at DESC")
@order = Order.where('user_id= ?', current_user.id)
end
# GET /products/new
def new
@product = Product.new
@order = Order.new
end
ビュー/受注/ _new_order.html.erb
<%= form_with(model: @orders) do |f| %>
<%= f.hidden_field :product_id, value: @product.id %>
<%= f.hidden_field :total, value: @product.price %>
<%= f.submit "Order", class: "btn btn-info btn-lg my-2" %>
<% end %>
ビュー/製品/ show.html .erb
# some code related to product show here and render new_order partial view
<%= render 'orders/new_order' %>
ルートファイル:
Rails.application.routes.draw do
# if user is signed in the root_path will be products#index
authenticated :user do
root 'products#index', as: :authenticated_root
end
root 'static_pages#index'
get '/index', to: 'static_pages#index'
get '/about', to: 'static_pages#about'
get '/featured', to: 'static_pages#featured'
post 'static_pages/thank_you'
# devise_for :users
devise_for :users, path: '', path_names: { sign_in: 'login', sign_out: 'logout', sign_up: 'register'}
resources :users
resources :products do
resources :comments
end
# get '/products/:id', to: 'products#show'
resources :orders, only: [:index, :show, :create, :destroy]
# resources :orders, except: [:new, :edit, :update]
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
私は製品#ショーのページに新しい注文を追加しようとしているときに、私は、サーバーのコンソールからこのエラーを取得する:
ActionController::RoutingError (No route matches [POST] "/products/1")
ご協力ありがとうございました
はまだ同じエラーを得たとして、次のインスタンス変数のタイプミスのエラーでした! 'ActionController :: RoutingError(ルートは[POST]と一致しません"/products/1 ")' – MManahi