多个Ruby on Rails模型关系

时间:2015-05-29 13:55:04

标签: ruby-on-rails ruby relational-database

我正在尝试通过具有来源和目的地的货件模型访问位置详细信息。

我想通过这样的电话访问位置信息:

Shipment.find(###).origin ->
   :id => "###", :cs => "Springfield, Mo", :latitude => "#####", :longitude => "####"

Shipment.find(###).dest ->
   :id => "###", :cs => "Springfield, Mo", :latitude => "#####", :longitude => "####"

我有以下设置

shipment.rb:

class Shipment < ActiveRecord::Base
  belongs_to :user
  has_many :vehicles, dependent: :destroy

  validates :origin_id, :dest_id, :presence => true

  attr_accessible :origin_id, :dest_id, (more attributes...)
end

location.rb

class Location < ActiveRecord::Base
  attr_accessible :cs, :latitude, :longitude
  geocoded_by :cs
  after_validation :geocode, :if => :cs_changed?
  has_many :shipments, :foreign_key => :origin_id
  has_many :shipments, :foreign_key => :dest_id
end

我认为是这样的:

has_one :origin, :class => "Location", :origin_id

scope :origin, -> (:origin_id) { Location.find(:origin_id)}

3 个答案:

答案 0 :(得分:2)

shipment.rb

var rootComponent = React.render(
    <Croot >..users & games here ...</Croot>,
    document.getElementById('lobbyArea')
);

答案 1 :(得分:2)

可以是

class Shipment < ActiveRecord::Base
...

  belongs_to :origin, class: 'Location', foreign_key: 'origin_id'
  belongs_to :dest, class: 'Location', foreign_key: 'dest_id'

end

旧轨道

class Shipment < ActiveRecord::Base
    ...

      belongs_to :origin, class_name: 'Location', foreign_key: 'origin_id'
      belongs_to :dest, class_name: 'Location', foreign_key: 'dest_id'

 end

然后是原点位置

Shipment.find(###).origin

然后是目的地位置

Shipment.find(###).dest

答案 2 :(得分:0)

由于您的Shipment模型实际上拥有外键,因此我认为这是belongs_to :origin情况。查看RoR guides了解更多信息。