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

编程入门 行业动态 更新时间:2024-10-10 10:32:05
本文介绍了如何将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用户与另一个现有模型相关联?

本文发布于:2023-11-28 14:09:36,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642724.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:相关联   如何将   模型   用户   Devise

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!