2011-12-18 70 views
1

我想我在我的应用程序中遵循轨道命名约定。但是当我在终端测试代码中时,我遇到了一些违背命名约定的错误。这里是我的终端会话:轨道命名惯例的麻烦

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' 

现在,当我尝试a.CtaTrains:

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 

从我的模型:

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 

我处于停滞状态,卡住了,撞我的头靠墙,等等。任何帮助都会很棒。

Rails的noobie这里....仿佛这一点并不明显.....

+0

运行时,你得到了同样的问题'捆EXEC轨console',而不是'irb'? – 2011-12-18 18:32:56

+0

完全没有。有用。你是男人。谢谢! – tbone 2011-12-18 18:37:27

+0

酷,作为答案添加,以便您可以标记正确以帮助未来的读者。 – 2011-12-18 18:45:14

回答

1

注意到你似乎是在IRB ......相反,我会尝试在使用活动记录类时留在轨道控制台中。

所以开始与

bundle exec rails console 
0

你所需要的就是一个路口表。见协会has_and_belongs_to_many

联结表将存储某个Neighbourhood和某个CtaTrain之间的链接。在这里,它是CtaLocation,但如果你不打算实际使用这个模型,你甚至可以不定义它。

例如,你可以实现它有三个表(街区,cta_trains和cta_trains_neighbourhoods),只有两个车型,如:

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 2011-12-18 18:47:41

+0

您仍然可以定义“连接模型”,而其他两个模型会更清晰。 – thoferon 2011-12-18 18:52:21

+0

好的,谢谢你的提示! – tbone 2011-12-18 18:55:13