Greetings good people!
I want to link 2 models through another model:
class Article < ActiveRecord::Base
...some callbacks...
has_many :article_images, dependent: :destroy
has_many :images, through: :article_images
...some methods...
end
class Image < ActiveRecord::Base
...some callbacks...
has_many :article_images, dependent: :destroy
has_many :articles, through: :article_images
...other methods...
end
class ArticleImage < ActiveRecord::Base
belongs_to :article
belongs_to :image
end
This works fine when I try to relate an article with an image using << or create():
art = Article.find 2 #=> <Article id: 2, category: 14, template: 2, param: "2">
art.images #=> <ActiveRecord::Associations::CollectionProxy []
img = Image.find 2 #=> <Image id: 2, filename: "testna2.jpg">
art.images << img #=> <ActiveRecord::Associations::CollectionProxy [#<Image id: 2, filename: "testna2.jpg">]>
The problem occurs when I try to do this the other way around:
img = Image.find 2
img.articles #=> ArgumentError: wrong number of arguments (1 for 0)
I didn't even come to the part where I assign an image object to a the article, looks like the association only works in one direction - art.images returns a collection, but img.articles causes an error.
Here's the crucial part of my schema (using mySQL):
create_table "articles", force: true do |t|
t.integer "category"
t.integer "template"
t.string "param"
end
create_table "article_images", force: true do |t|
t.integer "article_id"
t.integer "image_id"
t.string "lang"
t.string "title"
t.text "desc"
end
create_table "images", force: true do |t|
t.string "filename"
end
Here's the trace (seems like the problem isn't caused by my models?):
2.0.0p247 :023 > img.articles
ArgumentError: wrong number of arguments (1 for 0)
from /home/ziga/.rvm/gems/ruby-2.0.0-p247@goopti-storefront/gems/activerecord-4.0.0/lib/active_record/associations/builder/association.rb:70:in `articles'
from (irb):23
from /home/ziga/.rvm/gems/ruby-2.0.0-p247@goopti-storefront/gems/railties-4.0.0/lib/rails/commands/console.rb:90:in `start'
from /home/ziga/.rvm/gems/ruby-2.0.0-p247@goopti-storefront/gems/railties-4.0.0/lib/rails/commands/console.rb:9:in `start'
from /home/ziga/.rvm/gems/ruby-2.0.0-p247@goopti-storefront/gems/railties-4.0.0/lib/rails/commands.rb:64:in `<top (required)>'
from bin/rails:4:in `require'
from bin/rails:4:in `<main>'
Does anyone have a clue what's going on? At first I used has_and_belongs_to_many to connect the Article and Image models, but then I figured it would be better to include a third model with some extra columns (apart from the ids). That doesn't seem to be such a good idea now...