【发布时间】:2016-07-08 08:21:39
【问题描述】:
我遇到了一些问题,我对保存嵌套属性的正确方法有点困惑。
我有两个模型、位置和产品以及一个名为 stock 的连接表,用于连接这两个模型。
class Location < ApplicationRecord
has_many :stocks
has_many :products, :through => :stocks
end
class Product < ApplicationRecord
has_many :stocks
has_many :locations, :through => :stocks
accepts_nested_attributes_for :locations
end
class Stock < ApplicationRecord
belongs_to :location
belongs_to :product
end
在我的控制器中,我有以下内容
class ProductsController < ApplicationController
def index
@products = Product.all
end
def new
@product = Product.new
@product.stocks.build
@locations = Location.all
end
def create
@product = Product.new(product_params)
if @product.save
flash[:notice] = "Successfully saved..."
redirect_to products_path
else
flash[:alert] = "Something went wrong, please check the values you entered"
redirect_to :back
end
end
但我认为我在操作上做错了,因为什么也没发生。我想要的是在创建产品时显示所有可能的位置,以便用户可以选择在哪些位置声明该产品应该存在。这自然会被库存模型跟踪。
有人愿意告诉我吗?
编辑:我对此做了一些修改,
我的新观点
<div class="input-field">
<%= f.label :product_name %>
<%= f.text_field :name, autofocus: true %>
</div>
<div class="input-field">
<%= f.label :price %>
<%= f.text_field :price, autofocus: true %>
</div>
<%= f.fields_for :stocks do |ff| %>
<div class="input-field">
<%= ff.collection_select :location_id, Location.all, :id, :structured_location , {:prompt => "Please Select Locations for Product"}, {multiple: true} %>
<%= ff.label :locations %>
</div>
<% end %>
<div class="row margin-top x-4">
<div class="col s12 center-align">
<%= f.submit "Update", class: "btn wave-effect pink darken-1 btn-large" %>
</div>
</div>
在 product.rb 模型中
class Product < ApplicationRecord
has_many :stocks
has_many :locations, :through => :stocks
accepts_nested_attributes_for :stocks
end
现在我可以选择位置,但是当我推送到产品控制器时,我发现 location_id 是不允许的
这是我的强大参数
def product_params
params.require(:product).permit( :name,:price, {stocks_attributes: [:location_id]} )
end
这是在控制台中发送的参数
Parameters: {"utf8"=>"✓", "authenticity_token"=>"751Z5I5nBwmYJwFeiXO3jyBnPxqr3Pdz0ohDpN96F0ybE9V4yeUgjt2QYDYZfNvWG4CAdhvGaxIaCmqD6Ka8qw==", "product"=>{"name"=>"Tires Cleaner", "price"=>"4", "stocks_attributes"=>{"0"=>{"location_id"=>["", "1"]}}}, "commit"=>"Update"}
【问题讨论】:
-
“什么都没有发生”是什么意思?错误?没有保存数据?等
-
你的强参数也需要这样:params.require(:product).permit(:name,:price,locations_attributes: [:id, :venue])
标签: ruby-on-rails ruby-on-rails-4 ruby-on-rails-5