【发布时间】:2016-06-24 14:00:27
【问题描述】:
我有一个 rails4 应用程序,但我刚刚意识到我忘记通过查找没有 product_id 的 db 对象向我的 IndustryProducts 表添加验证。
用户可以在接受nested_attributes 的产品表单中创建product,以便通过collection_select 选择一个或多个industries。到目前为止一切正常,但是当我尝试将IndustryProducts 表中的presence 验证添加到外键字段(product_id 和industry_id)时,我在选择一个或多个行业后提交表单时收到错误消息:Industry products product can not be blank 和 Industry products is invalid。如果我什么都不选,那么我当然会收到至少选择一个的消息。
我错过了什么?如何验证product_id 和industry_id 都存在于IndustryProducts 表中?
class Product < ActiveRecord::Base
has_many :industry_products, dependent: :destroy
has_many :industries, through: :industry_products
accepts_nested_attributes_for :industry_products, reject_if: :all_blank, allow_destroy: true
validates_associated :industry_products
end
class Industry < ActiveRecord::Base
has_many :industry_products
has_many :products, through: :industry_products
#accepts_nested_attributes_for :industry_products #THIS LINE MAKES NO DIFFERENCE; tried with and without it
validates :name, presence: { messsage: "can not be blank" }
end
class IndustryProduct < ActiveRecord::Base
belongs_to :product
belongs_to :industry
#accepts_nested_attributes_for :industry #THIS LINE NEITHER MAKES DIFF; tried with and without it
#IF I PUT THESE LINES IN THEN I GET THE ERRORS I MENTIONED ABOVE
validates :product, presence: { message: "can not be blank" }
validates :industry, presence: { message: "can not be blank" }
end
产品形式:
<%= form_for @product,....
<%= f.collection_select :industry_ids, Industry.all.order(name: :asc), :id, :name, {}, { multiple: true, class: "form-control" } %>
.....
产品的strong_params:
params.require(:product).permit( :name, industry_ids: [], .....)
通过 POST 请求发送的参数:
"product"=>{"name"=>"asdfasfasdfqqqq", "industry_ids"=>["4", "8"], "description"=>"", .........}
控制器
def new
@product = Product.new
@product.industry_products.build
end
def create
@product = current_user.products.new(product_params)
if @product.save
......
end
【问题讨论】:
-
你能展示你的控制器动作吗?
-
sebsonic2o,我加了。
-
我认为这里的问题是使用
validates_associated :industry_products,但只提供通过关联的ID。作为调试步骤,如果您删除它,是否会保存正确的记录? -
我试过了,在这种情况下我只收到
Industry products product can not be blank错误消息。我在考虑参数中的空字符串,这会导致问题吗?顺便提一句。我真的不明白为什么数组中的第一个是空的。 -
我认为您可能希望在您的收藏选择中添加 { include_hidden: false }。 Industry_ids 参数中的空白可能是罪魁祸首...
标签: ruby-on-rails validation nested-attributes jointable