失去了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