Ruby on rails 获取NoMethodError时如何修复用户1对多关联;未定义的方法';用户id';,你是说?“用户”;

Ruby on rails 获取NoMethodError时如何修复用户1对多关联;未定义的方法';用户id';,你是说?“用户”;,ruby-on-rails,ruby-on-rails-5,Ruby On Rails,Ruby On Rails 5,我正在尝试实现一个用户模型,它与文章有一对多的关联。因此,我添加了一个User.rb模型 class User < ApplicationRecord has_many :articles before_save { self.email = email.downcase } validates :username, presence: true, uniqueness: { case_sensitive: false }, length: { min

我正在尝试实现一个用户模型,它与文章有一对多的关联。因此,我添加了一个User.rb模型

class User < ApplicationRecord
  has_many :articles
  before_save { self.email = email.downcase }
  validates :username, presence: true,
      uniqueness: { case_sensitive:  false },
      length: { minimum: 3, maximum: 25 }

  VALID_EMAIL_REGEX = /\A\S+@.+\.\S+\z/i
  validates :email, presence: true,
      uniqueness: { case_sensitive: false },
      length: { maximum: 105 }, format: { with: VALID_EMAIL_REGEX }
end
最后是我在articles_controller.rb文件中的更改函数:

def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end
我运行了railsdb:migrate,这样就不会有问题了。我在Stackoverflow上看到一些人说我应该加上

@article.user\u id=当前的\u user.id

但已经这么做了,什么也没发生

我不断地发现这个错误:

NoMethodError(未定义的#的'user_id'方法) 你是说?使用者

我不知道还能尝试什么。我从RubyonRails开始,所以请记住这一点


非常感谢您的阅读,希望有人知道一个修复方法。

首先,确保您的迁移能够顺利完成;然后您的
schema.rb
也应该包括
user\u id

然后,尝试将创建新文章的行更改为:

@article=current_user.articles.new(article_参数)
或者,您可以设置

@article.user=当前用户

在文章控制器中,您需要将
用户id
添加到允许的参数中

def article_params
  params.require(:article).permit(:title, :text, :user_id)
end

文章表中没有
用户id
。上次迁移通过了吗?尝试重新启动rails服务器谢谢,成功了。我在另一个我忘记的终端上打开了服务器,但实际上迁移并没有通过。很高兴这有帮助:)当你不明白为什么有些东西不起作用时,重启服务器通常是第一件事
ActiveRecord::Schema.define(version: 2019_02_26_124924) do
  create_table "articles", force: :cascade do |t|
    t.string "title"
    t.text "text"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "comments", force: :cascade do |t|
    t.string "commenter"
    t.text "body"
    t.integer "article_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.index ["article_id"], name: "index_comments_on_article_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "username"
    t.string "email"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end
def create
  @article = Article.new(article_params)
  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end
def article_params
  params.require(:article).permit(:title, :text, :user_id)
end