问候好人!

我想通过另一个模型链接两个模型:



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


当我尝试使用<
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模型,但是后来我认为最好包括第三个模型,该模型带有一些额外的列(除了ids)。现在这似乎不是一个好主意...

最佳答案

好的,看起来我发现了导致错误的原因,但是我仍然不确定为什么-我在代码中使用了attr_accessor,问题似乎出在它的名字上。

我改变了



attr_accessor :association


进入

attr_accessor :assoc


尽管我在重命名之前就已经注释掉了使用@association变量的方法,但我的问题却突然消失了。

我仍然不确定attr_accessor如何影响模型和关联,但我认为“关联”可能是rails中的保留字(尽管在任何列表中都找不到)。

如果有人在处理同一件事时遇到麻烦,那么我建议您检查代码中是否存在可疑的attr_accessors或变量和方法名。

我仍然无法对发生的事情做出最终结论,因此,如果您认为自己对此问题有所了解,请发表评论。

10-08 07:34
查看更多