Rails: create on has_one association

后端 未结 4 1177
鱼传尺愫
鱼传尺愫 2020-12-22 23:05

Hi (huge Rails newbie here), I have the following models:

class Shop < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :title, :user_id, :         


        
4条回答
  •  不思量自难忘°
    2020-12-23 00:07

    First of all, here is how to do what you want:

    @user = current_user
    @shop = Shop.create(params[:shop])
    @user.shop = @shop
    

    Now here's why your version did not work:

    You probably thought that this might work because if User had a has_many relation to Shop, @user.shops.create(params[:shop]) would work. However there is a big difference between has_many relations and has_one relations:

    With a has_many relation, shops returns an ActiveRecord collection object, which has methods that you can use to add and remove shops to/from a user. One of those methods is create, which creates a new shop and adds it to the user.

    With a has_one relation, you don't get back such a collection object, but simply the Shop object that belongs to the user - or nil if the user doesn't have a shop yet. Since neither Shop objects nor nil have a create method, you can't use create this way with has_one relations.

提交回复
热议问题