Ruby on Railsの新機能です。私は、Rails 5.1、アクティブレコードシリアライザ、ドアキーパ、宝石を作ってRails APIを作っています。rails APIとのHABTMの関係が機能しない
私はOrder
テーブルを持っており、多くの製品があります。注文と商品の関係は多対多です。
注文モデル:
class Order < ApplicationRecord
validates_presence_of :brute, :net
has_and_belongs_to_many :products
end
製品モデル:
class Product < ApplicationRecord
belongs_to :category
validates_presence_of :name, :price
validates_uniqueness_of :name
has_and_belongs_to_many :orders
end
私はorders_products
という名前の結合テーブルを持っています。
注文シリアライザ:
class OrderSerializer < ActiveModel::Serializer
attributes :id, :discount, :brute, :net, :payed, :payed_at, :products
def products
object.products.map do |product|
ProductSerializer.new(product, scope: scope, root: false, event: object)
end
end
end
製品シリアライザ:
class ProductSerializer < ActiveModel::Serializer
attributes :id, :name, :price, :description
has_one :category
end
注文コントローラ:
module Api
class OrdersController < ApiController
before_action :set_order, only: [:show, :update, :destroy]
# GET /api/orders
def index
@orders = Order.all
render json: @orders
end
# GET /api/orders/1
def show
render json: @order
end
# POST /api/orders
def create
@order = Order.new(order_params)
if @order.save
render json: @order, status: :created, location: api_order_url(@order)
else
render json: @order.errors, status: :unprocessable_entity
end
end
# PATCH/PUT /api/orders/1
def update
if @order.present?
if @order.update(order_params)
render json: @order
else
render json: @order.errors, status: :unprocessable_entity
end
end
end
# DELETE /api/orders/1
def destroy
@order.destroy if @order.present?
end
private
# Use callbacks to share common setup or constraints between actions.
def set_order
@order = Order.find(params[:id])
rescue ActiveRecord::RecordNotFound
Rails.logger.error{ 'Order record is not found' }
nil
end
# Only allow a trusted parameter "white list" through.
def order_params
params.require(:order).permit(:discount, :brute, :net, :payed, :payed_at, product_ids: [])
end
end
end
私はポストマン/不眠症のようなAPIジェネレータアプリからいくつかのためのJSONデータを投稿し、注文はオーダーテーブルに保存されていますが、データはorders_products
のジョインテーブルに保存されていません。
注文JSONの私の要求(POST http://localhost:3000/api/orders):
{
"discount": 110,
"brute": 100,
"net": 200,
"payed": null,
"payed_at": null,
"product_ids": [3]
}
が、私は解決策を見つけることを試みるが、私は失敗しました。
私はシリアライザを使用しないので、コードのいくつかの部分にあまり慣れていません。コード内のどこに商品を追加することができますか?たぶんあなたはこれも処理されているビュー(erb)ファイルをコピーすることができます.. – Maxence
私も同じ問題に直面しています。しかし、アクティブレコードシリアライザの宝石を使用している間はerbファイルはありません。 –