在以下情况下,我使用嵌套形式的has_many/has_many关系存在问题。
我有文章,可以有很多单位(公斤,袋子等)。通过我的表格,我需要记录这些数据。
因此,我决定对关系has_many使用嵌套形式,但出现错误:ArgumentError (No association found for name 'article_unit_of_measurements'. Has it been defined yet?)
这是我的类(class)代码:
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();
这是我的 Controller :
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:数据单元已填充
最佳答案
代替
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
和article_unit_of_measurements
。因此,错误
ArgumentError (No association found for name 'article_unit_of_measurements'
关于select - 找不到名称关联-Nested Form Rails 4,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22241625/