In Rails, how can I automatically update a User to own a newly created object of another class within the new object's Create method?

前端 未结 3 1871
旧巷少年郎
旧巷少年郎 2021-01-26 02:35

My application has Users and Dwellings. When a user creates a dwelling, the user becomes the owner

3条回答
  •  孤独总比滥情好
    2021-01-26 03:23

    UPDATE: Just to be clear, I misunderstood the user/dwelling relationship in the answer below, so this is not a solution to the problem.


    I think you're misunderstanding how associations work. With a belongs_to/has_many relationship, only the model that belongs to (in this case, Dwelling) has a foreign key pointing to the other record (in this case, User through the foreign key owner_id). The other record (User) does not need a key for every association, which would be redundant.

    Likewise, you don't need to assign @dwelling to current_user.dwelling, nor do you need to save the current_user. Just saving @dwelling after building it in current_user.properties.build(params[:dwelling]) should be enough.

提交回复
热议问题