2015-07-13 51 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

谢谢,它现在有效。 –