Postrgresql looking for the wrong many to many table with Rails 3
**UPDATE: I found this:
"Active Record expects intermediate join tables to be named with a concatenation of the tables it joins, in alphabetical order."
Sigh... **
I have 3 models: images, videos and keywords. Images and videos look basically the same and I've been trying to do everything the same for them with regards to keywords. But adding a keyword to an image works fine while adding a keyword to a video doesn't.
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
This works:
images_controller.开发者_StackOverflow社区rb
@image.keywords << Keyword.new(:word => "test")
This:
videos_controller.rb
@video.keywords << Keyword.new(:word => "test")
Gives me this error:
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
When I check the console for adding a keyword to an image, it correctly looks for "images_keywords" Why does it look for "keywords_videos" for videos???
What is different about the two?
When using has_and_belongs_to_many
, the name of the join table needs to have the related models listed in alphabetical order, ie: keywords_videos
not videos_keywords
.
精彩评论