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.
First of all, here is how to do what you want:
Now here’s why your version did not work:
You probably thought that this might work because if User had a
has_manyrelation to Shop,@user.shops.create(params[:shop])would work. However there is a big difference betweenhas_manyrelations andhas_onerelations:With a
has_manyrelation,shopsreturns an ActiveRecord collection object, which has methods that you can use to add and remove shops to/from a user. One of those methods iscreate, which creates a new shop and adds it to the user.With a
has_onerelation, 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 acreatemethod, you can’t usecreatethis way withhas_onerelations.