我是个 Rails 菜鸟,如果这是我的一个明显错误,我深表歉意。 我正在尝试创建两个模型的关联,图像和类别,其中每个图像实例与类别具有“has_and_belongs_to_many”关系,反之亦然。我想让类别在图片上传表单中显示为复选框,以允许将每张图片附加到多个类别,但不断出现此错误:
undefined method `association' for #<ActionView::Helpers::FormBuilder:0x000001011cf370>
我已经坚持了大约 2 天,并检查了所有其他看起来像类似问题的帖子以及谷歌搜索,尝试了各种教程并从头开始了好几次。到目前为止没有任何效果,我有点陷入了死胡同。这就是我现在所拥有的。类别和图像模型自己工作得很好,据我所知 categories_images 迁移也很好。我已经检查了表格并且可以从控制台和 GUI 将数据插入到图像和类别中。一切正常,但无法弄清楚为什么当我尝试建立关联时表单会抛出此错误。非常感谢对此的任何帮助!
这是我目前拥有的。如果有任何帮助,我正在使用 Rails 3.2.11 和 Ruby 1.9.3!
图片.rb
class Image < ActiveRecord::Base
attr_accessible :description, :name
has_and_belongs_to_many :categories
accepts_nested_attributes_for :categories
end
分类.rb
class Category < ActiveRecord::Base
attr_accessible :name
validates_presence_of :name
has_and_belongs_to_many :images
end
类别图片.rb
class CategoriesImages < ActiveRecord::Migration
def change
create_table :categories_images do |t|
t.integer :category_id
t.integer :image_id
end
add_index :categories_images, [:category_id,:image_id]
end
end
创建图像.rb
类 CreateImages < ActiveRecord::Migration
def change
create_table :images do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
创建类别.rb
class CreateCategories < ActiveRecord::Migration
def change
create_table :categories do |t|
t.string :name
t.timestamps
end
end
end
这是带有“f.association”行的图像上传表单(目前没有任何文件上传功能),这似乎是突出显示的问题。
<%= form_for(@image) do |f| %>
<% if @image.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@image.errors.count, "error") %> prohibited this image from being saved:</h2>
<ul>
<% @image.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :description %><br />
<%= f.text_area :description %>
</div>
**<%= f.association :categories, :as => :checkboxes %>**
<div class="actions">
<%= f.submit %>
</div>
<% end %>
最佳答案
错误表明“关联”不是可用的方法。是否依赖于像 simple_form 这样的 gem?你包括这个吗?
关于ruby-on-rails - "Undefined method ` association ' "为关联模型添加表单复选框时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19744159/