2015-07-13 49 views
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 

回答

2

的方法你has_one得到的是不同的

TripPlan.find(1).build_place 

你也得到create_place方法

+0

謝謝,它現在有效。 –