在嵌套属性的情况下验证连接表

时间:2016-03-09 22:59:54

标签: ruby-on-rails validation nested-attributes jointable

我有一个rails4应用程序,只是意识到我忘记通过查找没有IndustryProducts的db对象来向我的product_id表添加验证。

用户可以在产品表单中创建product,以便nested_attributes通过industries选择一个或多个collection_select。到目前为止一切正常,但是当我尝试在presence表中将IndustryProducts验证添加到外键字段(product_idindustry_id)时,我收到了有关提交的错误消息选择一个或多个行业后的表单:Industry products product can not be blankIndustry products is invalid。如果我什么都不做,那么我当然会得到至少选择一个的消息。

我错过了什么?如何验证product_id表中是否存在industry_idIndustryProducts

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

1 个答案:

答案 0 :(得分:2)

我必须在产品模型中添加inverse_of: :product,现在一切正常:

class Product < ActiveRecord::Base
  has_many :industry_products, dependent: :destroy, inverse_of: :product
  .......