失去了validation失败的思维,保存了嵌套模型

没头绪。 一直在阅读文档和示例,并没有能够弄清楚这一点。 我可能错过了一些非常明显的东西。

楷模

class Item  :destroy accepts_nested_attributes_for :item_ownerships validates :collection, :presence => true end class ItemOwnership  true validates :item_id, :presence => true end class User < ActiveRecord::Base has_many :item_ownerships end 

调节器

 class ItemsController  :toggle_item_owned_state) do @collection = current_user.collections.find(params[:collection_id]) end def new @item = Item.new collection_id: @collection.id @item_ownership = @item.item_ownerships.build(:owned => true, :user => current_user, :item => @item) end def create @item = @collection.items.build(item_params) @item_ownership = @item.item_ownerships.build(:user => current_user, :item => @item) #byebug if @item.save! redirect_to collection_items_path(@collection) else flash.now[:alert] = "There was a problem saving this item." render "new" end end def item_params params.require(:item).permit(:name, item_ownerships_attributes: [:id, :owned, :user, :item]) end end 

视图

  <div class="form-group ">   true, :placeholder => "Item Name", :class => "form-control", :'aria-describedBy' => "itemNameBlock" %>  Item     Owned  

当我提交表单时,它失败并出现以下错误:

validation失败:项目所有权用户不能为空,项目所有权项目不能为空

使用调试器,我在保存之前查看了@item和@item_ownerships中的值,它们如下:

 (byebug) @item # (byebug) @item_ownership # 

我假设在提交表单时,实例化@item,将填充并保存关联中的所有值。

我将继续尝试找到类似的问题或文章,但任何帮助将不胜感激。

更新

有趣的是,如果我删除了复选框视图中的fields_for,则两个模型都会保存,不会出现validation错误。

 Post Parameters provided as requested: {"utf8"=>"✓", "authenticity_token"=>"TMPET9Oq9eH8vbk7REVnmKEB5X8BqycSkio5XXdwsLSVqs8/Soz+uMyGJJZCnpOQgbwBESnkKmLts8oQKKiG/Q==", "item"=>{"name"=>"testg", "item_ownerships_attributes"=>{"0"=>{"owned"=>"1"}}}, "commit"=>"Save", "collection_id"=>"71"} 

我花了一段时间,但我终于明白了。 我完全误解了嵌套模型的工作原理。

在’create’中,两个模型(items和item_ownerships_是使用行中的item_params构建的:

 @item = @collection.items.build(item_params) 

结果,实现@item_ownerships的以下行是不必要的。 validation失败有两种方式:

1)用户失败,因为没有通过item_params传递的用户信息2)项目失败,因为我应该使用:inverse_of执行validation(参考这篇文章: http : //michaelwelburn.com/2014/02/10/ rails-4-nested-object-creation-and-parent-presence-validation-error / )

无论如何,感谢任何回复并正在考虑回应的人。