我已经设置has_many和has_many:通过Order,User,Product和Order_detail模型之间的关联作为连接表。Rails - has_many:通过关联+保存关联数据
型号:
class Order < ActiveRecord::Base
has_many :order_details
belongs_to :user
has_many :products, through: :order_details
end
class OrderDetail < ActiveRecord::Base
belongs_to :order
belongs_to :product
end
class Product < ActiveRecord::Base
has_many :order_details
has_many :orders, through: :order_details
end
class User < ActiveRecord::Base
has_many :orders
end
如何自动连接表ORDER_DETAILS保存。 现在数据只保存到订单表中。 需要保存所有产品order_tables为当前的订单和用户
class OrdersController < ApplicationController
before_action :authenticate_user!
def index
@order = Order.all
end
def new
# @order = Order.new
@order = current_user.orders.new
end
def create
@order = current_user.orders.new(order_params)
@order.date = Date.today.to_s
if @order.save
# i think this is bad wrong to implementation of functional)
# params[:product_id].each do |detail_product_id|
# @order.order_details.product_id = detail_product_id
# @order.order_details.user_id = current_user
# @order.order_details.save
flash[:success] = "Order was successfully submitted"
redirect_to new_order_path
else
render :new
end
end
private
def order_params
params.require(:order).permit(:date, :product_id => [])
end
end
我的架构:
create_table "order_details", force: true do |t|
t.integer "order_id"
t.integer "product_id"
t.integer "quantity"
t.integer "price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
end
create_table "orders", force: true do |t|
t.integer "user_id"
t.date "date"
end
add_index "orders", ["user_id"], name: "index_orders_on_user_id", using: :btree
create_table "orders_products", id: false, force: true do |t|
t.integer "order_id"
t.integer "product_id"
end
create_table "products", force: true do |t|
t.string "product_name"
t.integer "product_price"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.boolean "available_status"
t.string "product_type"
end
您可能需要[nested_attributes(http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods。html)为这个 –