简体   繁体   English

将关联从has_many转换为has_one

[英]Convert an association from has_many to a has_one

I have two related models TripPlan and Place. 我有两个相关的模型TripPlan和Place。

class TripPlan < ActiveRecord::Base
  has_many :places
end

class Place < ActiveRecord::Base
  belongs_to :trip_plan
end

There's a corresponding migration for the places table: 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

So each TripPlan can have several places and each Place belongs to a single trip plan. 因此,每个TripPlan可以有多个地点,并且每个Place都属于一个行程计划。 But now I need a has_one / belongs_to relation between these models. 但是,现在我需要这些模型之间的has_one / belongs_to关系。 I modified TripPlan model as follows: 我修改了TripPlan模型,如下所示:

class TripPlan < ActiveRecord::Base
  has_one :place
end

But now if I try TripPlan.find(1).place.build it throws an error: 但是现在,如果我尝试TripPlan.find(1).place.build它将引发错误:

undefined method 'build' for nil:NilClass

The methods you get with has_one are different has_one获得的方法不同

TripPlan.find(1).build_place

You'll also get the create_place method 您还将获得create_place方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM