Search code examples
ruby-on-railsruby-on-rails-4simple-formhas-many-throughfields-for

Simple form- select collection and set up has_many through


How to display products divided into three parts(three different filter like: product_1, product_2, product_3 ) and need choose only one product from each part

After submit. I should to save all that products for one order.

I have 4 tables: Users Orders Order_details Products

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

I am not sure how to write strong params for that situation and how create that objects for save data.

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

Solution

  • for select collection and get 3 different ids from form, that works for me..

    post: ~ products_ids => {array ids}

    = 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")