添加表单复选框时错误我有点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上,如果有帮助的话!
Image.rb
class Image < ActiveRecord::Base
attr_accessible :description, :name
has_and_belongs_to_many :categories
accepts_nested_attributes_for :categories
end
Category.rb
class Category < ActiveRecord::Base
attr_accessible :name
validates_presence_of :name
has_and_belongs_to_many :images
end
categories_images.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
create_images.rb
类CreateImages < ACTIV电子线上学习记录::迁移
def change
create_table :images do |t|
t.string :name
t.text :description
t.timestamps
end
end
end
create_categories.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 %>
我看不到任何依赖错误或警告,但也可能是用它做。有什么方法可以检查吗?谢谢! – user2396842
除了您已经看到的内容外,不会有任何错误。你从哪里得到代码? “关联”似乎是来自“simple_form”gem(https://github.com/plataformatec/simple_form)的方法。您需要将其添加到您的gem文件,捆绑包中,然后确保您正确使用它。 github页面有很多文档。 – toms
谢谢你们!你们都是绝对正确的。我想我得到了来自不同来源的代码。我安装了simple_form gem,并将:checkboxes更改为:check_boxes,它起到了一定的作用。干杯! – user2396842