【问题标题】:Can implement a has_and_belongs_to_many association可以实现一个 has_and_belongs_to_many 关联
【发布时间】:2013-01-11 17:39:45
【问题描述】:

我对 HABTM 与 rails 3.2.11 的关联有点困惑。

我有一个图像模型:

class Image < ActiveRecord::Base
  attr_accessible :description, :name, :image, :article_ids
  has_and_belongs_to_many :articles
end

还有文章模型:

class Article < ActiveRecord::Base
  has_and_belongs_to_many :images
  attr_accessible :content, :name, :image_ids
end

我创建了一个迁移:

class CreateImagesArticlesTable < ActiveRecord::Migration
  def self.up
    create_table :images_articles, :id => false do |t|
        t.references :image
        t.references :article
    end
    add_index :images_articles, [:image_id, :article_id]
    add_index :images_articles, [:article_id, :image_id]
  end

  def self.down
    drop_table :images_articles
  end
end

然后我做了 rake db:migrate

现在我在更新图片时显示复选框以连接文章和图片:

%div
  - @articles.each do |article|
    = check_box_tag "article_ids[]", article.id
    = article.name

当我选中第一个复选框并更新它无法创建关联时,错误是:

ImagesController#update 中的 ActiveRecord::StatementInvalid

Mysql2::Error: 表 'project_development.articles_images' 不存在:SELECT articles.* FROM articles INNER JOIN articles_images ON articles.id = articles_images.article_id在哪里articles_images.image_id = 78

参数是:

{"utf8"=>"✓", "_method"=>"放", "authenticity_token"=>"5qUu72d7asba09d7zbas7a9azsdas8a8dss", "图像"=>{"名称"=>"测试", "描述"=>"测试描述", "article_ids"=>[]}, "article_ids"=>["1"], "提交"=>"更新图片", "id"=>"78-test"}

我在 MySQL Workbench 中看到了该表,但我无法查看它,因为它是:

错误:project_development.images_articles:表数据不可编辑,因为没有为表定义主键

【问题讨论】:

  • witg HABTM 导轨不会创建额外的表。请改用has_many through

标签: mysql ruby-on-rails-3 has-and-belongs-to-many


【解决方案1】:

迁移错误,表名加入了两个模型名的复数形式,但是是按字母顺序排列的,即是articles_images而不是images_articles。

无论哪种方式,最好有一个连接模型,然后是一个带有:through 选项的has_many。

【讨论】:

  • 谢谢,我会尝试使用 has_many 并在成功时接受答案。
【解决方案2】:

最后我改为将表迁移到articles_images并将视图更正为:

- @articles.each do |article|
  = check_box_tag "image[article_ids][]", article.id, @image.articles.include?(article)
  = article.name

这现在适用于 HABTM。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多