У меня есть две моделей, два отношения между нимиRails имеет много отношения
class Tracking
include Mongoid::Document
belongs_to :origin_courier, :class_name => "Courier", foreign_key: "origin_courier_id"
belongs_to :destination_courier, :class_name => "Courier", foreign_key: "destination_courier_id"
end
class Courier
include Mongoid::Document
has_many :origins, class_name: 'Tracking', foreign_key: "origin_courier_id"
has_many :destinations, class_name: 'Tracking', foreign_key: "destination_courier_id"
end
Когда я задаю курьер к origin_courier вновь созданное слежения, он прекрасно работать.
1.9.3p194 :015 > t = Tracking.new
=> #<Tracking _id: 4fbcc2772cfb397930000003, _type: nil, created_at: nil, updated_at: nil, origin_courier_id: nil, destination_courier_id: nil>
1.9.3p194 :016 > t.origin_courier = Courier.last
=> #<Courier _id: 4fbcbb072cfb397657000004, _type: nil, created_at: 2012-05-23 10:25:11 UTC, updated_at: 2012-05-23 10:25:11 UTC>
1.9.3p194 :017 > t
=> #<Tracking _id: 4fbcc2772cfb397930000003, _type: nil, created_at: nil, updated_at: nil, origin_courier_id: BSON::ObjectId('4fbcbb072cfb397657000004'), destination_courier_id: nil>
1.9.3p194 :018 > t.save
=> true
1.9.3p194 :019 > t
=> #<Tracking _id: 4fbcc2772cfb397930000003, _type: nil, created_at: 2012-05-23 10:57:14 UTC, updated_at: 2012-05-23 10:57:14 UTC, origin_courier_id: BSON::ObjectId('4fbcbb072cfb397657000004'), destination_courier_id: nil>
Но когда я задаю курьера к destination_courier вновь созданного слежения, он дублирует значение origin_courier
1.9.3p194 :020 > t2 = Tracking.new
=> #<Tracking _id: 4fbcc3002cfb397930000004, _type: nil, created_at: nil, updated_at: nil, origin_courier_id: nil, destination_courier_id: nil>
1.9.3p194 :021 > t2.destination_courier = Courier.last
=> #<Courier _id: 4fbcbb072cfb397657000004, _type: nil, created_at: 2012-05-23 10:25:11 UTC, updated_at: 2012-05-23 10:25:11 UTC>
1.9.3p194 :022 > t2.save
=> true
1.9.3p194 :023 > t2
=> #<Tracking _id: 4fbcc3002cfb397930000004, _type: nil, created_at: 2012-05-23 11:00:39 UTC, updated_at: 2012-05-23 11:00:39 UTC, origin_courier_id: BSON::ObjectId('4fbcbb072cfb397657000004'), destination_courier_id: BSON::ObjectId('4fbcbb072cfb397657000004')>
Как я могу решить эту проблему?
Спасибо.
Очень странно. Пробовали ли вы Courier.last.origins << Tracking.new и Courier.last.destinations << Tracking.new? –
@soundar это все тот же случай ... не знаю почему – Dante