我有一个rails4应用程序,只是意识到我忘记通过查找没有IndustryProducts
的db对象来向我的product_id
表添加验证。
用户可以在产品表单中创建product
,以便nested_attributes
通过industries
选择一个或多个collection_select
。到目前为止一切正常,但是当我尝试在presence
表中将IndustryProducts
验证添加到外键字段(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 for product:
params.require(:product).permit( :name, industry_ids: [], .....)
使用POST请求发送的params:
"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
答案 0 :(得分:2)
我必须在产品模型中添加inverse_of: :product
,现在一切正常:
class Product < ActiveRecord::Base
has_many :industry_products, dependent: :destroy, inverse_of: :product
.......