Rails: create on has_one association

Viewed 63727

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

class Shop < ActiveRecord::Base
  belongs_to :user
  validates_uniqueness_of :title, :user_id, :message => "is already being used"
end

and

class User < ActiveRecord::Base
  has_one :shop, :dependent => :destroy
end

When I'm about to create a new shop, I get the following error:

private method `create' called for nil:NilClass

This is my controller:

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

I've tried different variations by reading guides and tutorials here and there, but I'm more confused than before and can't get it to work. Any help would be greatly appreciated.

4 Answers

A more concise way to do this is with:

@user.create_shop(params[:shop])

See methods added by has_one in the Ruby on Rails guides.

Just to add to above answers -

@user.create_shop(params[:shop])

Above syntax creates new record but it subsequently deletes similar existing record.

Alternatively, if you do not want to trigger delete callback

Shop.create(user_id: user.id, title: 'Some unique title')

This thread might be helpful. Click here

Related