[英]Convert an association from has_many to a has_one
我有兩個相關的模型TripPlan和Place。
class TripPlan < ActiveRecord::Base
has_many :places
end
class Place < ActiveRecord::Base
belongs_to :trip_plan
end
Places表有一個相應的遷移:
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可以有多個地點,並且每個Place都屬於一個行程計划。 但是,現在我需要這些模型之間的has_one / belongs_to關系。 我修改了TripPlan模型,如下所示:
class TripPlan < ActiveRecord::Base
has_one :place
end
但是現在,如果我嘗試TripPlan.find(1).place.build
它將引發錯誤:
undefined method 'build' for nil:NilClass
has_one
獲得的方法不同
TripPlan.find(1).build_place
您還將獲得create_place
方法
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.