找不到名称的关联 - 嵌套表格Rails 4

时间:2014-03-07 04:42:00

标签: select ruby-on-rails-4 nested-forms nested-attributes has-many

对于以下情况,我使用嵌套表单遇到has_many / has_many关系问题。

我有文章,这可以有很多单位(Kg,包等)。通过我的表格,我需要记录这些数据。

所以我决定使用带有关系has_many的嵌套表单,但是我有一个错误:ArgumentError (No association found for name 'article_unit_of_measurements'. Has it been defined yet?)

这是我的Classes代码:

class Article < ActiveRecord::Base
    has_many :unit_of_measurements, :through => :article_unit_of_measurements
    accepts_nested_attributes_for :article_unit_of_measurements
end

class ArticleUnitOfMeasurement < ActiveRecord::Base
    belongs_to :article
    belongs_to :unit_of_measurement

    accepts_nested_attributes_for :unit_of_measurement
end


class UnitOfMeasurement < ActiveRecord::Base
    has_many :articles, :through => :article_unit_of_measurements
end

在我的表单中使用jquery插件select2.js将我的选择单元显示为标签。

= simple_form_for([:shop, @article], html: {class: 'form-horizontal' }) do |f|
  .col-md-10
    = f.input :name, placeholder: "Name", :input_html => {:class => 'form-control'}, label: false
  %label.col-md-2.control-label{for: "unit_of_measurement_id"} Unidad de medida
    .col-md-10
      %select#unit-select-measure.select2{:name =>"article[article_unit_of_measurements_attributes][#{Time.now.to_s}][unit_of_measurement_id]", :style => "width:100%;;padding: 0;border: none;", :multiple => true}
        - @unitOfMeasurement.each do |unit|
           %option{:value => "#{unit.id}"}
             = unit.name
   %button.btn.btn-primary{type: "submit"} Guardar
:javascript
  $('#unit-select-measure').select2();

这是我的控制者:

class Shop::ArticlesController < ApplicationController
 def new
    @article = Article.new
    @unitOfMeasurement = UnitOfMeasurement.all
    render layout: false
  end

  def create
    article = Article.new(article_parameters)
    if article.save
      flash[:notice] = "Lorem ipsum dolor sit amet."
      redirect_to :action => :index
    else
      flash[:error] = "Lorem ipsum dolor sit amet."
      redirect_to :action => :index
    end
  end

  private
  def article_parameters
    params.require(:article).permit(:name, article_unit_of_measurements_attributes: [:id, :article_id, :unit_of_measurement_id])
  end
end

P.D:数据单位已填充

1 个答案:

答案 0 :(得分:10)

替换

class Article < ActiveRecord::Base
    has_many :unit_of_measurements, :through => :article_unit_of_measurements
    accepts_nested_attributes_for :article_unit_of_measurements
end

class Article < ActiveRecord::Base
    has_many :article_unit_of_measurements   ## Added association
    has_many :unit_of_measurements, :through => :article_unit_of_measurements
    accepts_nested_attributes_for :article_unit_of_measurements
end

您错过了使用has_many association的{​​{1}}。

因此,错误article_unit_of_measurements