问题
I think I have followed the rails naming conventions in my app. But when I am in the terminal testing code I am coming across some errors that go against naming conventions. Here is my terminal session:
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'
Now when I try 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
From my models:
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
I am at a standstill, stuck, banging my head against the wall, etc. Any help would be fabulous.
Rails noobie here....as if this point is not obvious.....
回答1:
Noticed that you appear to be in IRB... Instead, I'd try to stay in the rails console when working with your active-record classes.
so start that with
bundle exec rails console
回答2:
What you need here is a junction table. See the association has_and_belongs_to_many
.
The junction table will store the links between a certain Neighbourhood
and a certain CtaTrain
. Here, it's CtaLocation but if you don't plan to actually use this model, you could even not define it.
For instance, you can achieve it With three tables (neighbourhoods, cta_trains and cta_trains_neighbourhoods) and only two models like :
class Neighbourhood
has_and_belongs_to_many :cta_trains
end
class CtaTrain
has_and_belongs_to_many :neighbourhoods
end
来源:https://stackoverflow.com/questions/8553768/trouble-with-rails-naming-conventions