ruby-on-rails - "Undefined method ` association ' "为关联模型添加表单复选框时出错

标签 ruby-on-rails ruby ruby-on-rails-3 activerecord

我是个 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/

相关文章:

ruby-on-rails - 如何从 Rails Controller 外部的给定 url 获取 url 段参数?

ruby - Rake:如何从任务内部输出任务列表?

ruby-on-rails - rails 装置 :has_many and :belongs_to

ruby-on-rails - 在 PostgreSQL 中使用 DISTINCT 选择列

ruby-on-rails - Rails 3 教程 10.4.2 : NoMethodError undefined method `admin?' for nil:NilClass

ruby-on-rails-3 - rails + sideqik...如何在特定日期和时间执行任务

ruby-on-rails-3 - 如何将多个文件附加到 ActionMailer 邮件对象? (没有它也会附加几个不需要的文本文件。)

mysql - 如何在本地找到我为 Rails 应用程序创建的数据库并将其加载到服务器?

ruby-on-rails - ruby - 评估从另一个方法返回的代码

ruby-on-rails - 如何找到运行 Rails 实例的本地端口?