如何将Devise用户与另一个现有模型相关联?

时间:2014-02-10 14:56:58

标签: ruby-on-rails devise ruby-on-rails-4

我是Ruby on Rails的新手,并设置了Devise进行身份验证。我在添加Devise之前创建了一个现有模型。该模型称为文章。我相信我已经做了我需要做的一切,以便使用association=(associate) "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"方法,这正是我需要做的。

这是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?问题中的流行答案。

我知道我犯了一个菜鸟错误。它是什么?

1 个答案:

答案 0 :(得分:1)

新的User实例需要先分配到@article ,然后才能访问任何实例的属性/关联。请尝试以下方法:

@article = Article.new(post_params) # Assign first
@article.user = current_user        # Then access attributes/associations

问题中发布的代码会产生nil:NilClass异常,因为user上正在调用@article关联,nil因为尚无任何内容分配给它

相关问题