如何通过创建记录,与两个外键有很多关联。

时间:2014-03-23 01:30:49

标签: ruby-on-rails database activerecord foreign-keys

我需要创建一个与位置相关联的路线。

class Location < ActiveRecord::Base
 has_many :routes,:foreign_key => "origin_id"
end

并且路线属于不同的位置:

class Route < ActiveRecord::Base
 belongs_to :origin, :class_name => 'Location', :foreign_key => 'location_id'
 belongs_to :destination, :class_name => 'Location', :foreign_key => 'destination_id'
  validates :origin, :presence => {:message => 'origin cannot be blank'}
end

location.routes.create({
                    :destination    => resort_location,
                    :destination_id => resort_location.id,
                    :total_distance => body['route_summary']['total_distance'],
                    :total_time     => body['route_summary']['total_time'],
                    :raw            => response.body
                   })

记录获得创建没有来源和目的地,即使我确实有存在验证。 谢谢你帮助我。

1 个答案:

答案 0 :(得分:0)

代码对我来说没问题 -

location.routes.create({
       :destination    => resort_location, #-> where is resort_location defined?
       :destination_id => resort_location.id,
       :total_distance => body['route_summary']['total_distance'],
       :total_time     => body['route_summary']['total_time'],
       :raw            => response.body
})

您的validates方法也需要针对特定​​属性(不是关系)。在你的情况下,它应该是这样的:

validates :location_id, presence: {message: 'You need an origin!'}

你有没有错误/日志?