【问题标题】:Postrgresql looking for the wrong many to many table with Rails 3Postgresql 使用 Rails 3 寻找错误的多对多表
【发布时间】:2011-05-27 03:21:51
【问题描述】:

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

“Active Record 期望中间连接表以它连接的表的串联命名,按字母顺序排列。”

叹息... **

我有 3 个模型:图片、视频和关键字。图像和视频看起来基本相同,我一直在努力为他们做所有关于关键字的事情。但是向图像添加关键字效果很好,而向视频添加关键字则不行。

关键字.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

图像.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”???

两者有什么不同?

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-03
      • 1970-01-01
      • 2020-05-16
      • 1970-01-01
      • 2012-06-22
      • 2013-01-06
      • 1970-01-01
      相关资源
      最近更新 更多