ruby-on-rails - 编辑页面没有保存更改 - Cocoon Gem
问题描述
如果我的语言不正确,请原谅我,我对 Rails 和 Ruby 还比较陌生。
我正在使用 Cocoon 从嵌套模型中当前存在的选项列表中进行选择,但我选择的选项永远不会保存。我几乎可以肯定这与我对控制器的建模方式有关,但我不确定错误在哪里。
我将在此处发布相关代码。
模型文件:
# product.rb
module Almacenear
class Product < Almacenear::ApplicationRecord
belongs_to :category, optional: true, inverse_of: :product
has_and_belongs_to_many :shops, inverse_of: :product
end
end
#shop.rb
module Almacenear
class Shop < Almacenear::ApplicationRecord
accepts_nested_attributes_for :products, :reject_if => :all_blank
end
end
控制器文件:
#shops_controller.rb
module Almacenear
module Grocermenu
class ShopsController < Almacenear::ApplicationController
before_action :authenticate_grocer!
before_action :find_shop, only: %i[edit update show]
helper Almacenear::Grocermenu::Engine.routes.url_helpers
include Almacenear::Grocermenu::Engine.routes.url_helpers
def update
if @shop.update(shop_params)
redirect_to almacenear_grocermenu.shop_path
else
render :edit
end
end
protected
def shop_params
params.require(:shop).permit(:business_name, :location,
products_attributes: [:id, :name, :category_id,
:product_type, :description, :measurement_unit,
:image, :other_id, :ean,
:image_file_name, :image_content_type, :image_file_size,
:image_updated_at, :img_url_web, :_destroy])
end
def find_shop
@shop = Almacenear::Shop.find(params[:id])
end
end
end
end
意见:
#_addproduct.html.erb
<%= simple_form_for @shop, url: url do |f| %>
<div id='products'>
<%= f.simple_fields_for :products do |product| %>
<%= render 'product_fields', :f => product %>
<% end %>
<div class='links'>
<%= link_to_add_association '+', f, :products, class:"btn btn-success" %>
</div>
</div>
<%= f.button :submit, value: 'Enviar', class: 'btn-success' %>
<% end %>
# _product_fields.html.erb
<div class='nested-fields'>
<%= f.select :id, Almacenear::Product.all.collect { |p| [ p.name, p.id ] }, { include_blank: true } %>
<%= link_to_remove_association '-', f , class:"btn btn-danger"%>
</div>
我得到的错误是,一旦它尝试加载almacenear_grocermenu.shop_path
,它会声明:
Couldn't find Almacenear::Product with ID=15 for Almacenear::Shop with ID=1
即,它会尝试显示与Almacenear::Shop 相关联的ID = 15 的产品,然后再将其保存到Almacenear::Shop 的product_ids 列表中。并且只是为了检查,如果我更新重定向到almacenear_grocermenu.shops_path
,即与当前登录的 Grocer 关联的商店列表,则不会有错误,但与该商店关联的产品列表也不会发生变化。
我最初还测试了将控制器中的线路从products_attributes: [...]
to更改为:product_ids => []
也没有保存任何内容。这是我在开始使用Cocoon Gem之前使用 Simple_Form 的关联和复选框时的遗留问题。这种情况下的错误是它只会忽略请求的更改。
最后,我想指出问题在于保存商店和产品之间的关联。部分addproducts伴随着另一个部分,用于编辑商店自己的字段,例如它的名称和地址,并且当对此进行更改时,它们确实保存到商店的值中。
抱歉,这篇文章太长了,我只是尽可能详细地说明了我的过程,这是我的第一篇文章,所以我希望它的措辞不会太差。任何帮助将不胜感激!
解决方案
推荐阅读
- java - Android P ,下载不开始使用下载管理器?
- php - Laravel Eloquent ID 作为数组键
- android - 解析存储在 ionic 3 中的常量中的 JSON 字符串
- java - JavaFX - 加载下一个场景时保留工具栏
- c++ - 如何将 C 类型“char *”存储到 C++ 向量中?
- selenium - 如何在 Appium 中使用现有的应用程序会话
- python - 没有名为 graphframes 的模块 Jupyter Notebook
- angular - 使用新值复制和更新对象并存储到数组
- gemfire - 无法为嵌入式 Apache Geode 缓存服务器操作在 Spring 上下文中定义的区域
- php - cart.php 只为最后一个产品返回想要的值