Rails - has_many:通过关联+保存关联数据

时间:2016-04-29 08:16:31

标签: ruby-on-rails ruby-on-rails-4 associations has-many-through has-many

我设置了has_many和has_many:通过Order,User,Product和Order_detail模型之间的关联作为连接表。

型号:

var itemsProcessed = 0;
for (var index = 0; index < uniqueIdentifiers.length; index++) {
    let uniqueIdentifier = uniqueIdentifiers[index];

    // Remove the reference
    this.database.removeFileReference(uniqueIdentifier, removeFileReferenceCallback.bind(uniqueIdentifier));
}

function removeFileReferenceCallback(removeReferenceError) {
    if (removeReferenceError !== null) {
        NotificationSystem.logReferenceNotRemoved(this, undefined);
    }

    // When all items are removed, use the callback
    if (++itemsProcessed === uniqueIdentifiers.length) {
        callback(null);
    }
};

如何自动保存连接表order_details。 现在数据仅保存到订单表。 需要将所有产品保存到order_tables以获取当前订单和用户

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

我的架构:

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

4 个答案:

答案 0 :(得分:1)

在您的视图中,为order_details添加字段,如:

     <%= f.fields_for :order_details do |od| %>
       <%= od.label 'your attribute for OrderDetail' %>
       <%=  # od.text_field 'your attribute' %>
     <% end %>

然后在您的模型中,接受order_details的嵌套属性 像:

    accepts_nested_attributes_for :order_details

这些是样本值,您可以将此逻辑与您的实际属性一起使用。

在您的控制器中,允许order_details的属性,如:

    params.require(:order).permit(:id, :name, order_details: [
      #attributes of order details
    ])

答案 1 :(得分:1)

假设product_ids是您希望添加到订单中的产品ID的数组,您可以尝试按以下方式分配它们,并且当您随后调用@ order.save时,Rails应自动为order_details创建这些关联记录/ p>

@order.products << Product.find_by_id(product_ids)

答案 2 :(得分:0)

我是否正确为控制器添加行? Order_controller:

  def create
    @order = current_user.orders.new(order_params)
    @order.products = Product.find_by_id(order_params[:product_ids])
    @order.date = Date.today.to_s
    if @order.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, order_details: [:product_id])
 end
end

订单型号:

  accepts_nested_attributes_for :order_details

我试图从3种不同类型的产品中保存。

product_details

  • 但是如何从每个部分获取一个产品ID?因为现在我只能从中选择一种产品

查看:

= simple_form_for(@order, html: {:class => 'well form-horizontal', :method  => :post, :action=> :create }) do |f|
    .col-xs-12.col-sm-6.col-md-8
    = render 'shared/error_messages', object: f.object
    %br
    = simple_fields_for :order_details do |od|
       = od.collection_radio_buttons :product_ids, Product.get_first_course, :id, :product_name ,:item_wrapper_class => 'inline'
      %hr
      = od.collection_radio_buttons :product_ids, Product.get_main_course, :id, :product_name, :item_wrapper_class => 'inline'
      %hr
      = od.collection_radio_buttons :product_ids, Product.get_drink, :id, :product_name,:item_wrapper_class => 'inline'
     %hr
   = f.button :submit, class: "btn btn-primary"

答案 3 :(得分:-1)

我将关联类型更改为HABTM,这对我的情况来说已经足够了。所以..

模型:

  class Order < ActiveRecord::Base
   has_and_belongs_to_many :products
   before_destroy { products.clear }
  end
  class Product < ActiveRecord::Base
   has_and_belongs_to_many :orders
  end

Order_controller:

def create
  order = current_user.orders.new(date: Date.today.to_s)
  @order_products = Product.where(id: order_params[:product_ids])
  order.products << @order_products
  if order.save
    #blalblal - sucsess
  else
    #blabla - alert-notice
  end