一段时间以来,我一直在为一个 Rails 问题绞尽脑汁,想验证我的发现。我试图让 Has_and_belongs_to_many 关系正常工作,但无法连接我的两个类,auctionItem 和 category。首先,这是我的迁移文件和解决问题之前的两个类:
迁移文件:
class AuctionItemsCategories < ActiveRecord::Migration
def up
create_table 'auction_items_categories', :id=>false do |t|
t.reference :auctionItem_id
t.references :category_id
end
end
def down
drop_table 'auction_items_categories'
end
end
类别.rb
class Category < ActiveRecord::Base
has_and_belongs_to_many :auction_items
end
拍卖物品.rb
class AuctionItem < ActiveRecord::Base
has_and_belongs_to_many :categories
end
创建 AuctionItem 的实例后,我尝试了
auction_item = AuctionItem.last
auction_item.categories
...并得到以下错误:
NoMethodError: undefined method `categories' for #<AuctionItem:0x0000010521b870>
经过一番研究,我发现将特定类添加到 has_and_belongs_to_many 有帮助:
类别模型
has_and_belongs_to_many :auction_items , :class_name => 'AuctionItem'
auction_item 模型
has_and_belongs_to_many :categories , :class_name => 'Category'
这解决了这个问题,我能够访问类别表。我继续尝试在拍卖品中添加一个类别:
auction_item.categories << category
然后我收到以下错误:
SELECT "auction_items".* FROM "auction_items" INNER JOIN "auction_items_categories" ON "auction_items"."id" = "auction_items_categories"."auction_item_id" WHERE "auction_items_categories"."category_id" = 2
SQLite3::SQLException: no such column: auction_items_categories.auction_item_id: SELECT "auction_items".* FROM "auction_items" INNER JOIN "auction_items_categories" ON "auction_items"."id" = "auction_items_categories"."auction_item_id" WHERE "auction_items_categories"."category_id" = 2
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: auction_items_categories.auction_item_id: SELECT "auction_items".* FROM "auction_items" INNER JOIN "auction_items_categories" ON "auction_items"."id" = "auction_items_categories"."auction_item_id" WHERE "auction_items_categories"."category_id" = 2
如果您注意到,查询正在尝试获取auction_item.id 而不是AuctionItem.id。为了使连接正常工作,我必须将迁移文件更改为以下内容:
class AuctionItemsCategories < ActiveRecord::Migration
def up
create_table 'auction_items_categories', :id=>false do |t|
t.integer :auction_item_id
t.integer :category_id
end
end
def down
drop_table 'auction_items_categories'
end
end
长话短说/TL DR 版本:对我来说,似乎当用多个单词命名你的类并使用驼峰式大小写时,如果它有一个下划线,rails 不会将你的复数类名单数化回它的原始状态。例如,我的类名是 AuctionItem ,它变成了模型的auction_items。不是搜索auctionitem.id,而是查找的sql 调用是auction_item.id,它是auction_items 的单数化版本。为什么不搜索auctionitem.id?以后在制作多词类的关联表时,是否使用单数下划线 id 版本的模型名称?