lightbots
lightbots

Reputation: 485

Rails - storing values - through association

I would like to store values in :quantity from the table below using the orders form but I am not sure how to do so for this specific table.

 create_table "order_items", force: true do |t|
    t.integer  "item_id"
    t.integer  "order_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "quantity"
    t.decimal  "price"
  end

The relationships are as follows

order model

has_many :order_items
has_many :items, :through => :order_items

item model

has_many :order_items
has_many :orders, :through => :order_items

OrderItem model

belongs_to :item
belongs_to :order

Upvotes: 3

Views: 64

Answers (1)

Richard Peck
Richard Peck

Reputation: 76784

You'll need to use accepts_nested_attributes_for and then use a nested form in Rails:

#app/models/order.rb
Class Order < ActiveRecord::Base
   has_many :order_items
   has_many :items, :through => :order_items

   accepts_nested_attributes_for :order_items
end

This will mean you will have to build the order_item object before you send the data so your form can use the f.fields_for method to handle the associative data, like this:

#app/controllers/orders_controller.rb
Class OrdersController < ApplicationController
   def new
      @order = Order.new
      @order.order_items.build
   end

   def create
      @order = Order.new(order_params)
      @order.save
   end

   private

   def order_params
      params.require(:order).permit(:order, :params, order_items_attributes: [:quantity])
   end

end

#app/views/orders/new.html.erb
<%= form_for @order do |f| %>
   <%= f.fields_for :order_items do |o| %>
       <%= o.text_field :quantity %>
   <% end %>
<% end %>

Upvotes: 2

Related Questions