Postgresql用Rails 3寻找错误的多对多表

时间:2011-05-27 03:21:51

标签: ruby-on-rails-3 postgresql many-to-many has-and-belongs-to-many

**更新:我发现了这个:

“Active Record期望中间连接表以字母顺序连接的表连接命名。”

...叹息 **

我有3个模特:图片,视频和关键字。图片和视频看起来基本相同,我一直在尝试为关键字做一切相同的事情。但是,为图像添加关键字可以正常工作,而向视频添加关键字则不然。

keyword.rb

has_and_belongs_to_many :cases
has_and_belongs_to_many :images
has_and_belongs_to_many :videos

video.rb

has_and_belongs_to_many :keywords

image.rb

has_and_belongs_to_many :keywords

schema.rb

create_table "images_keywords", :id => false, :force => true do |t|
  t.integer  "image_id"
  t.integer  "keyword_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

create_table "videos_keywords", :id => false, :force => true do |t|
  t.integer  "video_id"
  t.integer  "keyword_id"
  t.datetime "created_at"
  t.datetime "updated_at"
end

这有效:

images_controller.rb

@image.keywords << Keyword.new(:word => "test")

此:

videos_controller.rb

@video.keywords << Keyword.new(:word => "test")

给我这个错误:

ActiveRecord::StatementInvalid in VideosController#create

PGError: ERROR:  relation "keywords_videos" does not exist
LINE 4:              WHERE a.attrelid = '"keywords_videos"'::regclas...
                                    ^
:             SELECT a.attname, format_type(a.atttypid, a.atttypmod), d.adsrc,      a.attnotnull
          FROM pg_attribute a LEFT JOIN pg_attrdef d
            ON a.attrelid = d.adrelid AND a.attnum = d.adnum
         WHERE a.attrelid = '"keywords_videos"'::regclass
           AND a.attnum > 0 AND NOT a.attisdropped
         ORDER BY a.attnum

当我检查控制台是否为图像添加关键字时,它正确查找“images_keywords”为什么它会为视频寻找“keywords_videos”???

两者有什么不同?

1 个答案:

答案 0 :(得分:4)

使用has_and_belongs_to_many时,联接表的名称需要按字母顺序列出相关模型,即:keywords_videos而不是videos_keywords