嵌套表格/质量分配,验证麻烦,has_many_through

时间:2016-12-21 22:20:41

标签: ruby-on-rails validation nested-forms has-many-through mass-assignment

好的,所以我无法理解我在哪里出错了。我正确设置了我的关联,并且我的新订单表单正常工作(注意:如果两个字段都填写完毕)。如果我只填写一个字段,对于一个项目订单,质量分配失败。我希望能够最终拥有3个字段,但如果只填写了1个或2个字段,那么一切都会很好,空字段会被忽略。我已经尝试了解了几个小时,现在我已经尝试过,我可以想到调试/承担这个问题。

视图/表单: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 %>

控制器操作:

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    

模特:

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

我希望这一切都清楚。我还是初学者,所以任何帮助都将不胜感激!感谢

0 个答案:

没有答案