Activerecord-association: create new object (find class)

后端 未结 3 1171
我在风中等你
我在风中等你 2021-02-06 18:47

I have an model with a relation, and I want to instantiate a new object of the relations type.

Example: A person has a company, and I have a person-obje

3条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-02-06 19:35

    You can also use build_association() in the relationship classes.
    Simplest way to use it is through the Model's __call, i.e. if your relation is something like $person->company, then you could instantiate the company with
    $company = $person->build_company()

    Note that this will NOT also make the "connection" between your objects ($person->company will not be set).
    Alternatively, instead of build_company(), you can use create_company(), which will save a new record and link it to $person

提交回复
热议问题