Ok, so I'm having trouble understanding where I'm going wrong here. I have my associations set up correctly and my new order form works correctly (note: if both fields are filled out). If I only fill out one field, for a one item order, the mass assignment fails. I want to be able to eventually have 3 fields but if only 1 or 2 of them are filled out, everything goes through fine, with the empty fields being ignored. I've tried to understand this for hours and now I've tried everyway I can think of debugging/undertanding this thing.
The view/form: new.html.erb
<%= form_for @order do |f| %>
<%= f.hidden_field :date, :value => Time.now %>
<%= f.fields_for :order_items do |f| %>
<%= f.collection_select :item_id, Item.all, :id, :item_type, :include_blank => true %>
<%= f.label "Quantity: "%>
<%= f.text_field :quantity %><br>
<% end %>
<%= f.submit %>
<% end %>
Controller actions:
def new
@order = Order.new
@order.order_items.build
@order.order_items.build #for 2 fields
end
def create
@user = current_user
@account = Account.find_or_create_by(user_id: @user.id)
@account.orders.create(params_check)
end
Models:
class Order < ApplicationRecord
has_many :order_items
has_many :items, through: :order_items
belongs_to :account
def order_items_attributes=(order_items_attributes)
order_items_attributes.each do |i, order_item_attributes|
#binding.pry
self.order_items.build(order_item_attributes)
end
end
end
class OrderItem < ApplicationRecord
belongs_to :order
belongs_to :item
**NOTE: ALL THESE VALIDATIONS SEEM TO BE USELESS**
#validates :item_id, :presence => {:message => "You must choose"}
#validates :quantity, :presence => {:message => "You must choose"}
#validates :order_id, :presence => {:message => "You must choose"}
#validates_presence_of :item_id, :message => "You must choose an item"
#validates_presence_of :quantity, :message => "You must enter the quantity"
end
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :account
has_many :orders, through: :account
end
class Account < ApplicationRecord
belongs_to :user
has_many :orders, dependent: :destroy
end
class Item < ApplicationRecord
#belongs_to :order
has_many :order_items
end
I hope that is all clear. I'm still a beginner so any help would be appreciated! Thanks