新对象归属不会与创建它的设计用户关联
当我的用户创建一个应该有他的 id
的对象时,id
会出现 nil
。想法为什么?
# controllers/units_controller.rb
class UnitsController < ApplicationController
before_filter :authenticate_user!
def new
@unit = Unit.new
@unit.user = current_user # also tried .user_id = current_user.id
[...]
# models/unit.rb
class Unit < ActiveRecord::Base
belongs_to :user
# :user has_many :units too
[...]
该对象已成功保存,但 user_id
字段为空(显示 nil
)。 没有抛出异常。保存时没有回调。
When my user creates an object that should have his id
on it, the id
comes out nil
. Ideas why?
# controllers/units_controller.rb
class UnitsController < ApplicationController
before_filter :authenticate_user!
def new
@unit = Unit.new
@unit.user = current_user # also tried .user_id = current_user.id
[...]
# models/unit.rb
class Unit < ActiveRecord::Base
belongs_to :user
# :user has_many :units too
[...]
The object is saved successfully, but with an empty user_id
field (showing nil
).
No exception is thrown. There is no callback on save.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您在标准 Rails 两步(#new (POST)-> #create)中执行此操作,则需要在 #create 操作中将 Unit 与 current_user 关联起来。
If you're doing this in the standard Rails two step (#new (POST)-> #create), then you need to associate Unit with current_user in the #create action.