0

如何展示產品分爲三個部分設立的has_many(三種不同的過濾器,如:product_1,product_2,product_3),並需要從每個部分簡單的形式 - 選擇集合,並通過

提交後只能選擇一個產品。我應該爲一個訂單保存所有的產品。

我有4個表: 用戶 訂單 ORDER_DETAILS 產品

class Order < ActiveRecord::Base 
    has_many :order_details 
    belongs_to :user 
    has_many :products, through: :order_details 
    accepts_nested_attributes_for :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 
    def self.get_first_course 
    Product.where(product_type: "exem_product_1") 
    end 
    def self.get_main_course 
    Product.where(product_type: "exem_product_2") 
    end 
    def self.get_drink 
    Product.where(product_type: "exem_product_3") 
    end 
end 

我不知道如何寫強有力的params用於在這種情況下,如何創建對象的保存數據。

class OrdersController < ApplicationController 
before_action :authenticate_user! 
def index 
    @order = Order.new 
    #I think need something like this..?! 
    #@order.order_details.build 
end 

def create 

end 

private 

def order_params 
    params.require(:order).permit(:date, :product_id => []) 
end 
end 

回答

0

爲選擇收集並從表格中獲得3個不同的ID,這對我有用..

post: 〜products_ids => {array ID}

= simple_form_for @order do |f| 
= render 'shared/error_messages', object: f.object 
= simple_fields_for :product_ids do |product| 
    = product.collection_select(nil, Product.get_first_course, :id, :product_name, 
           {prompt: "Select first course" },class: "form-control product-select") 
    = product.collection_select(nil, Product.get_main_course, :id, :product_name, 
          {prompt: "Select first course"},class: "form-control product-select") 
1

你可以做這樣的事情在你的控制器:

class OrdersController < ApplicationController 
before_action :authenticate_user! 
def index 
    @order = Order.all 
end 

def new 
    @order = Order.new 
end 

def create 
    @order = current_user.orders.new(order_params) 
    if @order.save 
    #your actions here 
    else 
    #your actions to rescue error 
    end 
end 

private 

def order_params 
    params.require(:order).permit(:date, :product_id => []) 
end 
end 

,並使用無線電按鈕集合簡單的形式,你必須做這樣的事情:

= 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 
    = f.collection_radio_buttons :product_ids, Product.get_first_course, :id, :product_name, :item_wrapper_class => 'inline' 
    %hr 
    = f.collection_radio_buttons :product_ids, Product.get_main_course, :id, :product_name, :item_wrapper_class => 'inline' 
    %hr 
    = f.collection_radio_buttons :product_ids, Product.get_drink, :id, :product_name,,:item_wrapper_class => 'inline' 
    %hr 
    = f.association :products, as: :radio_buttons 
    = f.button :submit, class: "btn btn-primary"