こんにちは良い人たち!
別のモデルを介して 2 つのモデルをリンクしたい:
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
<< または 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">]>
これを逆に実行しようとすると、問題が発生します。
img = Image.find 2
img.articles #=> ArgumentError: wrong number of arguments (1 for 0)
画像オブジェクトを記事に割り当てる部分にも行きませんでした。関連付けは一方向にしか機能しないようです.art.imagesはコレクションを返しますが、img.articlesはエラーを引き起こします.
これが私のスキーマの重要な部分です(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
トレースは次のとおりです (問題は私のモデルが原因ではないようですか?):
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>'
誰が何が起こっているのか手がかりを持っていますか? 最初はhas_and_belongs_to_manyを使用して Article モデルと Image モデルを接続していましたが、(ID 以外の) 追加の列を持つ 3 番目のモデルを含める方がよいと考えました。それは今ではあまり良い考えではないようです...