2011-12-18 8 views
1

私のアプリでは、レールの命名規則に従ったと思います。しかし、私が端末テストコードに入っているとき、私は命名規則に反するいくつかのエラーに遭遇しています。レールの命名規則に問題がある

class Neighborhood < ActiveRecord::Base 

    has_many :cta_trains, :through => :cta_locations 
    has_many :cta_locations, :foreign_key => :neighborhood_id 

end 

class CtaTrain < ActiveRecord::Base 

    has_many :neighborhoods, :through => :cta_locations 
    has_many :cta_locations, :foreign_key => :cta_train_id 

end 

class CtaLocation < ActiveRecord::Base 

    belongs_to :neighborhood 
belongs_to :cta_train 

end 

私が停止しています、立ち往生、私の頭を叩いて:私のモデルから

irb(main):012:0> a.CtaTrains 
    CtaTrain Load (0.4ms) SELECT "cta_trains".* FROM "cta_trains" INNER JOIN "cta_locations" ON "cta_trains"."id" = "cta_locations"."CtaTrain_id" WHERE "cta_locations"."neighborhood_id" = 24 
SQLite3::SQLException: no such column: cta_locations.CtaTrain_id: SELECT "cta_trains".* FROM "cta_trains" INNER JOIN "cta_locations" ON "cta_trains"."id" = "cta_locations"."CtaTrain_id" WHERE "cta_locations"."neighborhood_id" = 24 
ActiveRecord::StatementInvalid: SQLite3::SQLException: no such column: cta_locations.CtaTrain_id: SELECT "cta_trains".* FROM "cta_trains" INNER JOIN "cta_locations" ON "cta_trains"."id" = "cta_locations"."CtaTrain_id" WHERE "cta_locations"."neighborhood_id" = 24 

:私はa.CtaTrainsをしようとすると、今

irb(main):010:0> a = _ 
=> #<Neighborhood id: 24, name: "Lincoln Park", created_at: "2011-12-03 20:29:00", updated_at: "2011-12-03 21:08:47", minlat: 41.91092, maxlat: 41.925658, minlng: -87.648761, maxlng: -87.636117> 
irb(main):011:0> a.cta_trains 
NoMethodError: undefined method `cta_trains' for #<Neighborhood:0x007fd666ee61e8> 
    from /usr/local/Cellar/ruby/1.9.2-p290/lib/ruby/gems/1.9.1/gems/activemodel-3.1.1/lib/active_model/attribute_methods.rb:385:in `method_missing' 

:ここに私のターミナルセッションでどんな助けも素晴らしいだろう。 noobieここ

のRails ....この点は明白ではないかのように.....あなたがここに必要なもの

+0

とあなたは同じ問題を得るかということを開始? –

+0

全くありません。できます。あなたは男です。ありがとうございました! – tbone

+0

クール、答えとして追加されますので、今後の読者に役立つように修正することができます。 –

答えて

1

たとえば、あなたは3つのテーブル(地域、cta_trainsとcta_trains_neighbourhoods)と同様に2つだけのモデルとそれを達成することができますあなたのアクティブレコードクラスで作業するときは、レールコンソールにとどまるようにしてください。

のでconsole`代わりに `irb`の`バンドルのexecレールを実行するときに

bundle exec rails console 
0

が交差テーブルです。アソシエーションhas_and_belongs_to_manyを参照してください。

接合テーブルには、特定のNeighbourhoodと特定のCtaTrainの間のリンクが格納されます。ここではCtaLocationですが、実際にこのモデルを使用する予定がない場合は、定義することさえできません。代わりに、私は思います...あなたはIRBにあるように見えることに気づい

class Neighbourhood 
    has_and_belongs_to_many :cta_trains 
end 

class CtaTrain 
    has_and_belongs_to_many :neighbourhoods 
end 
+0

私は、結合モデルに手動で関連付けを追加できる必要があります。この場合、HABTMの規約は、has_many => throughよりも良い関係になりますか? – tbone

+0

"接合モデル"を定義することはできますが、他の2つはより明確になります。 – thoferon

+0

よろしくお願いします。 – tbone