关于mysql:可以实现一个has_and_belongs_to_many关联 | 珊瑚贝

Can implement a has_and_belongs_to_many association


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

我有一个图像模型:

1
2
3
4
class Image < ActiveRecord::Base
  attr_accessible :description, :name, :image, :article_ids
  has_and_belongs_to_many :articles
end

及文章型号:

1
2
3
4
class Article < ActiveRecord::Base
  has_and_belongs_to_many :images
  attr_accessible :content, :name, :image_ids
end

我创建了一个迁移:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
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

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

1
2
3
4
%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″=>”a?””,
“_method”=>”放”,
“authenticity_token”=>”5qUu72d7asba09d7zbas7a9azsdas8a8dss”,
“图像”=>{“名称”=>”测试”,
“描述”=>”测试描述”,
“article_ids”=>[]},
“article_ids”=>[“1”],
“提交”=>”更新图片”,
“id”=>”78-test”}

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

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

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


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

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

  • 谢谢,我会尝试使用 has_many 并在成功时接受答案。


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

1
2
3
@articles.each do |article|
  = check_box_tag“image[article_ids][]”, article.id, @image.articles.include?(article)
  = article.name


这现在适用于 HABTM。


来源:https://www.codenong.com/14283672/

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_9839.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?