2016-07-01 5 views
0

HABTMの関係には、MaintenanceOrderMaintenanceという2つのモデルがあります。一方HABTMの命名規則の問題

I have two models that are similar, and I'm wondering if this is the cause of the error? 

@maintenance.maintenances 
=> ActiveRecord::StatementInvalid: Could not find table 'maintenance_orders_maintenances' 
@maintenance_order.maintenances 
=> ActiveRecord::StatementInvalid: Could not find table 'maintenance_orders_maintenances' 

create_table :maintenances_maintenance_orders, id: false do |t| 
    t.belongs_to :maintenance, index: true 
    t.belongs_to :maintenance_order, index: true 
end 

をその後、私はエラーが発生します。移行が参加するテーブルを作成に関して

create_table :maintenance_orders do |t| 
    ... 
end 
create_table :maintenances do |t| 
    ... 
end 

以下のように宣言された、私は私が持っている場合は気づいもし私が持っていれば、エラーが次のような結合テーブルを示唆するように:

create_table :maintenance_orders_maintenances, id: false do |t| 
    t.belongs_to :maintenance_order, index: true 
    t.belongs_to :maintenance, index: true 
end 

すべて正常に動作します。しかし、私が理解する限り、HABTMの定義によって、モデルが宣言されている順序は重要ではないので、この質問をしています。だから...名前はとても似ているので、ちょうど私がこのようにしなければならない蛇のケースがある(おそらくmaintenances_maintenanceが紛らわしい)か... ...?これに関するルールは?

+0

デフォルトでは、Railsはテーブル名をアルファベット順に並べます。 'maintenance_order'は' maintenances'の前に来ますので、 ':maintenance_orders_maintenances'は、どのテーブルに名前が付けられるのか –

答えて

1

デフォルトでは、Railsはテーブル名をアルファベット順にジョイン・テーブル名で指定します。 maintenance_ordermaintenancesの前に来るので、:maintenance_orders_maintenancesは、その表に名前が付けられると予想されるものです。詳細は、http://edgeguides.rubyonrails.org/active_record_migrations.html#creating-a-join-tableを参照してください。

Railsが期待するものから離れている場合は、テーブル名を自分で設定できますが、標準の命名手順に従う方が良いでしょう。

すべてのRailsガイドを読んでみる価値はあることに注意してください。レール知識をそのようにきれいに整えることができます。