我想我已经遵循了我的应用程序中的rails命名约定。但是,当我在终端测试代码时,我遇到了一些违反命名约定的错误。以下是我的终端会话:
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 here....as如果这一点不明显.....
发布于 2011-12-19 02:44:51
注意到你看起来像是在IRB...相反,在使用活动记录类时,我会尽量留在rails控制台中。
那么就从下面开始
bundle exec rails console发布于 2011-12-19 02:43:35
这里你需要的是一个连接表。请参阅关联has_and_belongs_to_many。
连接表将存储某个Neighbourhood和某个CtaTrain之间的链路。在这里,它是CtaLocation,但是如果你不打算实际使用这个模型,你甚至可以不定义它。
例如,您可以使用三个表(neighbourhoods,cta_trains和cta_trains_neighbourhoods)和只有两个模型来实现它,例如:
class Neighbourhood
has_and_belongs_to_many :cta_trains
end
class CtaTrain
has_and_belongs_to_many :neighbourhoods
endhttps://stackoverflow.com/questions/8553768
复制相似问题