【发布时间】:2014-02-10 14:56:58
【问题描述】:
我对 Ruby on Rails 非常陌生,并且已经设置了 Devise 进行身份验证。我有一个在添加设计之前创建的现有模型。该模型称为文章。我相信我已经完成了我需要做的一切,以便使用 "assigns an associated object to this object. Behind the scenes, this means extracting the primary key from the associate object and setting this object’s foreign key to the same value" 的 association=(associate) 方法,这正是我需要做的。
这是 Devise 的用户模型:
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
has_one :article
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
end
这是我的文章模型:
class Article < ActiveRecord::Base
belongs_to :user
validates :name, presence: true, length: { minimum: 5 }
end
这是我的迁移:
class AddUserRefToArticles < ActiveRecord::Migration
def change
add_reference :articles, :user, index: true
end
end
这是我 articles_controller.rb 的创建方法:
def create
@article.user = current_user
@article = Article.new(post_params)
if @article.save
redirect_to @article
else
render 'new'
end
end
这是我的控制器运行时发生的情况:
NoMethodError in ArticlesController#create
undefined method `user=' for nil:NilClass
突出显示的代码是@article.user = current_user。至少我很高兴知道我写的那行代码类似于我在发布之前在这里看到的Devise how to associate current user to post? 问题中的流行答案。
我知道我犯了一个新手错误。这是什么?
【问题讨论】:
标签: ruby-on-rails devise ruby-on-rails-4