【问题标题】:How to associate a Devise User with another existing model?如何将设计用户与另一个现有模型相关联?
【发布时间】: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


    【解决方案1】:

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

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

    问题中发布的代码产生了一个nil:NilClassexception,因为user 关联正在@article 上调用,它是nil,因为还没有分配任何东西

    【讨论】:

    • 成功了!谢谢。但是,你能解释一下@article = Article.new(post_params) 到底发生了什么吗?我看不出它与将 User 实例分配给任何东西有什么关系。
    • 除非你给实例变量@article赋值,否则它将是nil。分配它Article.new 意味着@article 现在是Article 的一个新实例——它不再是nilArticle 的实例与 User 设置器有关联,这是您将 current_user 分配给的对象。
    • Michael - 基本上您需要放置 article.user = current_user 的原因是,当在数据库中创建新记录时,“articles”表中的“user”字段将填充 id current_user 的。这就是如何建立用户和文章之间的关系。 Devise 为您提供了“current_user”对象,除了该设计不参与该过程。该关系是“活动记录关联”,请阅读以获取更多信息guides.rubyonrails.org/association_basics.html
    • 你可以用一行代码来简化它:@article = current_user.build_article(post_params)guides.rubyonrails.org/…
    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-14
    • 2022-10-16
    相关资源
    最近更新 更多