【问题标题】:How to create a record through, has many association with two foreign keys.如何通过创建记录,与两个外键有很多关联。
【发布时间】:2014-03-23 01:30:48
【问题描述】:

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

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
                   })

即使我确实有存在验证,也可以在没有来源和目的地的情况下创建记录。 感谢您帮助我。

【问题讨论】:

  • 尝试使用列名而不是关系,例如 validates :location_id

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


【解决方案1】:

代码对我来说看起来不错 -

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!'}

您对此有任何错误/日志吗?

【讨论】:

  • :destination => resort_location 这是错误的,只有 id 是必需的
猜你喜欢
  • 2023-01-12
  • 1970-01-01
  • 2020-04-24
  • 1970-01-01
  • 2012-08-08
  • 2011-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多