如何将Devise用户与另一个现有模型相关联? [英] How to associate a Devise User with another existing model?

查看:60
本文介绍了如何将Devise用户与另一个现有模型相关联?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Ruby on Rails的新手,并设置了Devise进行身份验证.我有一个在添加Devise之前创建的现有模型.该模型称为文章.我相信我已经做了所有需要做的事情,才能使用这正是我需要做的.

I am very new to Ruby on Rails and have setup Devise for authentication. I have an existing model that I created prior to adding Devise. That model is called Article. I believe I have done everything I need to do in order to use the association=(associate) method that "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" which is exactly what I need to do.

这是Devise的用户模型:

Here is Devise's User model:

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

这是我的Article模型:

Here is my Article model:

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

这是我的控制器运行时发生的情况:

And here is what happens when my controller runs:

NoMethodError in ArticlesController#create
undefined method `user=' for nil:NilClass

突出显示的代码是 @ article.user = current_user .我至少很高兴得知我编写了类似于

The highlighted code is @article.user = current_user. I was at least glad to know that I wrote that line of code similar to the popular answer in the Devise how to associate current user to post? question that I saw on here before posting this one.

我知道我在犯一个菜鸟错误.什么事?

I know I'm making a rookie mistake. What is it?

推荐答案

之前,需要将一个新的 User 实例分配给 @article 您可以访问任何实例的属性/关联.请尝试以下操作:

A new User instance needs to be assigned to @article before you can access any of the instance's attributes/associations. Try the following:

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

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

The code posted in the question yields a nil:NilClassexception because the user association is being invoked on @article, which is nil because nothing has yet been assigned to it.

这篇关于如何将Devise用户与另一个现有模型相关联?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆