0

I'm a bit confused about a HABTM association with rails 3.2.11.

I have an Image model:

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

And an article model:

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

I created a migration:

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

Then I did rake db:migrate

Now I display checkboxes to connect articles and images when I update an image:

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

When I check the first checkbox and update it can't create the association, the error is:

ActiveRecord::StatementInvalid in ImagesController#update

Mysql2::Error: Table 'project_development.articles_images' doesn't exist: SELECT articles.* FROM articles INNER JOIN articles_images ON articles.id = articles_images.article_id WHERE articles_images.image_id = 78

Params is:

{"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"5qUu72d7asba09d7zbas7a9azsdas8a8dss", "image"=>{"name"=>"Test", "description"=>"Testdescription", "article_ids"=>[]}, "article_ids"=>["1"], "commit"=>"Update image", "id"=>"78-test"}

I see the table in MySQL Workbench, but I cannot look into it since it sais:

Error: project_development.images_articles: table data is not editable because there is no primary key defined for the table

user929062
  • 807
  • 4
  • 12
  • 33

2 Answers2

1

The migration is wrong, the table name join the plural of the two model names, but they are ordered alphabetically, i.e., it is articles_images not images_articles.

Either way, it is better to have a join model and then a has_many with the :through option.

Serabe
  • 3,834
  • 19
  • 24
0

In the end I changed to migration of table to articles_images and corrected the view to:

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

This now works fine with HABTM.

user929062
  • 807
  • 4
  • 12
  • 33