简体   繁体   中英

How to associate a Devise User with another existing model?

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.

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

Here is my Article model:

class Article < ActiveRecord::Base
  belongs_to :user
  validates :name, presence: true, length: { minimum: 5 }
end

Here is my migration:

class AddUserRefToArticles < ActiveRecord::Migration
    def change
      add_reference :articles, :user, index: true
    end
end

Here is my create method from my 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

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM