问题描述
嗨(这里是 Rails 新手),我有以下模型:
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
和
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
这是我的控制器:
@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:
@user = current_user
@shop = Shop.create(params[:shop])
@user.shop = @shop
现在这就是您的版本不起作用的原因:
Now here's why your version did not work:
您可能认为这可能有效,因为如果 User 与 Shop 有 has_many
关系,@user.shops.create(params[:shop])
会起作用.然而,has_many
关系和 has_one
关系之间存在很大差异:
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:
通过 has_many
关系,shops
返回一个 ActiveRecord 集合对象,该对象具有可用于向用户添加商店和从用户删除商店的方法.其中一种方法是 create
,它创建一个新商店并将其添加给用户.
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.
使用 has_one
关系,您不会返回这样的集合对象,而是返回属于用户的 Shop 对象 - 如果用户还没有商店,则返回 nil.由于 Shop 对象和 nil 都没有 create
方法,因此您不能以这种方式将 create
与 has_one
关系一起使用.
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.
这篇关于Rails:在 has_one 关联上创建的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!