0
我有兩個相關的模型TripPlan和Place。將關聯從has_many轉換爲has_one
class TripPlan < ActiveRecord::Base
has_many :places
end
class Place < ActiveRecord::Base
belongs_to :trip_plan
end
有針對地表中有相應的遷移:
class CreatePlaces < ActiveRecord::Migration
def change
create_table :places do |t|
t.references :trip_plan, index: true
t.timestamps null: false
end
end
end
因此,每個TripPlan可以有幾個地方,每個地方只屬於一個旅行計劃。但是現在我需要這些模型之間的has_one/belongs_to關係。我修改TripPlan模型如下:
class TripPlan < ActiveRecord::Base
has_one :place
end
但現在,如果我嘗試TripPlan.find(1).place.build
它拋出一個錯誤:
undefined method 'build' for nil:NilClass
謝謝,它現在有效。 –