将关联从 has_many 转换为 has_one
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
table:
的地方有相应的迁移
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
使用has_one
获得的方法不同
TripPlan.find(1).build_place
您还将获得 create_place
方法
我有两个相关模型 TripPlan 和 Place。
class TripPlan < ActiveRecord::Base
has_many :places
end
class Place < ActiveRecord::Base
belongs_to :trip_plan
end
table:
的地方有相应的迁移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
使用has_one
获得的方法不同
TripPlan.find(1).build_place
您还将获得 create_place
方法