Ruby on rails 自参考模型
我有两个表Townsid,name和Connectionsfrom\u id,to\u id。 连接不是对称的 如何在rails中对此进行建模,以便使用@town.nearnear\u townsRuby on rails 自参考模型,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有两个表Townsid,name和Connectionsfrom\u id,to\u id。 连接不是对称的 如何在rails中对此进行建模,以便使用@town.nearnear\u towns 编辑:@town.nearner_towns是to_id为@townfrom_id指定的城镇,我会这样做: #app/models/town.rb Class Town < ActiveRecord::Base has_many :connections, foregin_key: "fr
编辑:@town.nearner_towns是to_id为@townfrom_id指定的城镇,我会这样做:
#app/models/town.rb
Class Town < ActiveRecord::Base
has_many :connections, foregin_key: "from_id"
has_many :nearby_towns, ->(ids) { where("to_id IN (?)", (ids)) }, through: :connections
end
这将允许您致电@town.nearear_towns,但我不确定您将如何定义哪些城镇应归类为附近城镇
我在代码中的做法是向您的协会发送一系列ID,允许您定义哪些城镇应归类为附近城镇has_many:towns,through::connections?如何定义附近城镇?要创建更好的答案,您确实需要向我们提供一些更详细的上下文抱歉,这个问题不精确。这个对我有用的有很多:附近的城镇,通过::连接,来源::到