【问题标题】:ActiveModel::MissingAttributeError (can't write unknown attribute `user_id`) on Heroku DeploymentHeroku 部署上的 ActiveModel::MissingAttributeError(无法写入未知属性 `user_id`)
【发布时间】:2018-07-12 01:58:33
【问题描述】:

我有一个应用程序,其工作方式类似于 Stackoverflow 的简单版本(提问、回答、投票)。它在我的计算机上运行良好,但是当我在 Heroku 上部署它时,我在 Heroku 日志中收到此错误:

ActiveModel::MissingAttributeError(无法写入未知属性user_id)。

在 Heroku 本身上,应用程序告诉我“出了点问题,请检查日志”

我的问题是 user_id 确实存在于我的表中。所以我真的不知道为什么它不知道这个属性。我也可以毫无问题地登录并创建用户。但是当我想创建一个新问题时,我得到了这个错误......

这里是问题控制器:

class QuestionsController < ApplicationController
  before_action :private_access, except: [:index, :show]

    def index
      @questions = if params[:term]
      Question.where("title iLIKE ? OR description iLIKE ?" , "%#{params[:term]}%", "%#{params[:term]}%")
      else 
      @questions = Question.all.order("updated_at DESC")
      end
    end 

    def new
      @question = Question.new
    end

     def create
      @question = Question.new(questions_params)
      @question.user = current_user
      if @question.save
        flash[:success] = "Fantastic #{@current_user.username} you posed a new question. Surely someone answers soon, stay tuned..."
        redirect_to root_path
      else
         render :new
      end
    end

     def show
        @question = Question.find(params[:id])
        @answer = Answer.new        
        @comment = Comment.new
        @vote = Vote.new
     end 

    def edit
      @question = Question.find(params[:id])
    end

    def update
      @question = Question.find(params[:id])
      if @question.update(questions_params)
      flash[:success] = "Bravo #{@current_user.username}, you updated your question!"
      redirect_to root_path
      else
      flash[:danger] = "Ups, something went wrong. Please try again..."
      render :new
      end
    end


    def destroy
     @question = Question.find(params[:id])
      if @question.destroy
      flash[:danger] = "Ok #{@current_user.username}, question was deleted!"
      redirect_to root_path
      else 
      flash[:danger] = "Ups, something went wrong. Please try again..."
      redirect_to root_path
      end 
    end


    def voteup
      question = Question.find(params[:id])
      question.votes.create(user: current_user)

      flash[:success] = "Thanks #{current_user.username} for voting!"
      redirect_to question_path
    end 


    def votedown
      question = Question.find(params[:id])
      question.votes.where(user: current_user).take.try(:destroy)

      flash[:danger] = "Vote deleted!"
      redirect_to question_path

    end 



    private
        def questions_params
            params.require(:question).permit(:title, :description, :answer_id, :user_id, :body, :votes, :term)
        end 

end

这里是我的架构:

   create_table "answers", force: :cascade do |t|
    t.text "body"
    t.bigint "question_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["question_id"], name: "index_answers_on_question_id"
    t.index ["user_id"], name: "index_answers_on_user_id"
  end

  create_table "comments", force: :cascade do |t|
    t.string "commentable_type"
    t.integer "commentable_id"
    t.integer "user_id"
    t.text "body"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "questions", force: :cascade do |t|
    t.string "title"
    t.text "description"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.bigint "user_id"
    t.index ["user_id"], name: "index_questions_on_user_id"
  end

  create_table "users", force: :cascade do |t|
    t.string "email", limit: 100
    t.string "password_digest"
    t.string "name", limit: 100
    t.string "username", limit: 50
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  create_table "votes", force: :cascade do |t|
    t.integer "voteable_id"
    t.string "voteable_type"
    t.string "user_id"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end

  add_foreign_key "answers", "questions"
end

我的模型关联应该没问题:

class User < ApplicationRecord
has_secure_password validations: false 

has_many :answers, dependent: :destroy
has_many :questions, dependent: :destroy
has_many :comments, dependent: :destroy
has_many :votes, dependent: :destroy



validates :email, uniqueness: true, format: /@/
validates :password, presence: true, on: :create
validates :password, length: {in: 6..20 }, allow_nil: true
validates :name, presence: true
validates :username, presence: true

结束

class Question < ApplicationRecord
validates :title, presence: true
validates :description, presence: true, length: {minimum:10, maximum:10000}

belongs_to :user
has_many :comments, as: :commentable, dependent: :destroy
has_many :answers, dependent: :destroy
has_many :votes, as: :voteable, dependent: :destroy

到目前为止我尝试了什么:

  • 重启 Heroku
  • 重新加载架构 (db:schema:load)
  • 哭了

非常感谢任何帮助。非常感谢提前

编辑:我尝试重置数据库,删除应用程序并再次迁移.... Heroku 似乎没有在问题中添加任何 user_id,还是我错了?它给了我以下内容

CREATE TABLE "questions" ("id" bigserial primary key, "title" character varying, "description" text, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
   -> 0.0137s
== 20180620183722 CreateQuestions: migrated (0.0138s) =========================

D, [2018-07-11T14:56:58.545105 #4] DEBUG -- :   ActiveRecord::SchemaMigration Create (1.6ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180620183722"]]
D, [2018-07-11T14:56:58.548517 #4] DEBUG -- :    (3.0ms)  COMMIT
I, [2018-07-11T14:56:58.548687 #4]  INFO -- : Migrating to CreateAnswers (20180624115634)
D, [2018-07-11T14:56:58.550810 #4] DEBUG -- :    (1.3ms)  BEGIN
== 20180624115634 CreateAnswers: migrating ====================================
-- create_table(:answers)
D, [2018-07-11T14:56:58.562192 #4] DEBUG -- :    (10.4ms)  CREATE TABLE "answers" ("id" bigserial primary key, "body" text, "question_id" bigint, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL, CONSTRAINT "fk_rails_3d5ed4418f"
FOREIGN KEY ("question_id")
  REFERENCES "questions" ("id")
)
D, [2018-07-11T14:56:58.573617 #4] DEBUG -- :    (4.7ms)  CREATE  INDEX  "index_answers_on_question_id" ON "answers"  ("question_id")
   -> 0.0228s
== 20180624115634 CreateAnswers: migrated (0.0229s) ===========================

D, [2018-07-11T14:56:58.577497 #4] DEBUG -- :   ActiveRecord::SchemaMigration Create (2.6ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180624115634"]]
D, [2018-07-11T14:56:58.580639 #4] DEBUG -- :    (2.6ms)  COMMIT
I, [2018-07-11T14:56:58.580776 #4]  INFO -- : Migrating to CreateUsers (20180705164230)
D, [2018-07-11T14:56:58.582856 #4] DEBUG -- :    (1.3ms)  BEGIN
== 20180705164230 CreateUsers: migrating ======================================
-- create_table(:users)
D, [2018-07-11T14:56:58.596461 #4] DEBUG -- :    (12.6ms)  CREATE TABLE "users" ("id" bigserial primary key, "email" character varying(100), "password_digest" character varying, "name" character varying(100), "username" character varying(50), "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
   -> 0.0135s
== 20180705164230 CreateUsers: migrated (0.0137s) =============================

D, [2018-07-11T14:56:58.603402 #4] DEBUG -- :   ActiveRecord::SchemaMigration Create (1.5ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180705164230"]]
D, [2018-07-11T14:56:58.606167 #4] DEBUG -- :    (2.1ms)  COMMIT
I, [2018-07-11T14:56:58.606393 #4]  INFO -- : Migrating to CreateComments (20180708124323)
D, [2018-07-11T14:56:58.609250 #4] DEBUG -- :    (1.4ms)  BEGIN
== 20180708124323 CreateComments: migrating ===================================
-- create_table(:comments)
D, [2018-07-11T14:56:58.622279 #4] DEBUG -- :    (9.5ms)  CREATE TABLE "comments" ("id" bigserial primary key, "commentable_type" character varying,"commentable_id" integer, "user_id" integer, "body" text, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
   -> 0.0129s
== 20180708124323 CreateComments: migrated (0.0130s) ==========================

D, [2018-07-11T14:56:58.624708 #4] DEBUG -- :   ActiveRecord::SchemaMigration Create (1.4ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180708124323"]]
D, [2018-07-11T14:56:58.627539 #4] DEBUG -- :    (2.5ms)  COMMIT
I, [2018-07-11T14:56:58.627685 #4]  INFO -- : Migrating to CreateVotes (20180709152735)
D, [2018-07-11T14:56:58.629887 #4] DEBUG -- :    (1.3ms)  BEGIN
== 20180709152735 CreateVotes: migrating ======================================
-- create_table(:votes)
D, [2018-07-11T14:56:58.639342 #4] DEBUG -- :    (8.6ms)  CREATE TABLE "votes" ("id" bigserial primary key, "voteable_id" integer, "voteable_type" character varying, "user_id" character varying, "created_at" timestamp NOT NULL, "updated_at" timestamp NOT NULL)
   -> 0.0094s
== 20180709152735 CreateVotes: migrated (0.0095s) =============================

D, [2018-07-11T14:56:58.642138 #4] DEBUG -- :   ActiveRecord::SchemaMigration Create (1.4ms)  INSERT INTO "schema_migrations" ("version") VALUES ($1) RETURNING "version"  [["version", "20180709152735"]]
D, [2018-07-11T14:56:58.644622 #4] DEBUG -- :    (2.1ms)  COMMIT
D, [2018-07-11T14:56:58.656312 #4] DEBUG -- :   ActiveRecord::InternalMetadata Load (1.5ms)  SELECT  "ar_internal_metadata".* FROM "ar_internal_metadata" WHERE "ar_internal_metadata"."key" = $1 LIMIT $2  [["key", "environment"], ["LIMIT", 1]]
D, [2018-07-11T14:56:58.671265 #4] DEBUG -- :    (5.5ms)  BEGIN
D, [2018-07-11T14:56:58.674884 #4] DEBUG -- :   ActiveRecord::InternalMetadata Create (1.7ms)  INSERT INTO "ar_internal_metadata" ("key", "value", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "key"  [["key", "environment"], ["value", "production"], ["created_at", "2018-07-11 14:56:58.671911"], ["updated_at", "2018-07-11 14:56:58.671911"]]
D, [2018-07-11T14:56:58.677921 #4] DEBUG -- :    (2.6ms)  COMMIT
D, [2018-07-11T14:56:58.680372 #4] DEBUG -- :    (2.1ms)  SELECT pg_advisory_unlock(2612648823889037010)
➜  RubyOnCrack git:(master) ✗

【问题讨论】:

  • 如果给定错误在控制器中,您能否也写下它的行号。
  • 您在heroku restart 之前运行过heroku run rake db:migrate 吗? Heroku 不会自动执行迁移。
  • 当我在 localhost 上运行它时它不会给我一个错误.....这也是为什么我有点迷茫并且不知道在哪里看确切......当我运行时它给我的 Heroku 日志:2018-07-11T13:57:02.233498+00:00 app[web.1]: F, [2018-07-11T13:57:02.233421 #4] FATAL -- : [978133b4-1604 -436e-a9d9-7420d2dcb436] ActiveModel::MissingAttributeError(无法写入未知属性user_id):
  • 您在初次部署迁移数据库后是否运行heroku run rake db:migrate
  • 是的,我做到了。我还删除了 heroku 和本地数据库并将其设置为新的,但相同

标签: ruby-on-rails ruby heroku


【解决方案1】:

我猜可能是这里抛出了错误?

def create
  @question = Question.new(questions_params)
  @question.user = current_user
  if @question.save
    flash[:success] = "Fantastic #{@current_user.username} you posed a new question. Surely someone answers soon, stay tuned..."
    redirect_to root_path
  else
     render :new
  end
end

出于好奇,你试过了吗:

def create
  @question = current_user.questions.build(questions_params)
  if @question.save
    flash[:success] = "Fantastic #{@current_user.username} you posed a new question. Surely someone answers soon, stay tuned..."
    redirect_to root_path
  else
     render :new
  end
end

如果这不起作用,您可以在控制台中创建新记录吗?

【讨论】:

  • 我试过这个,它仍然给我一个错误。但有趣的是,当我尝试使用控制台时,它给了我以下信息:=> #......我不太明白为什么我可以在我的应用程序上创建问题但不能使用控制台???
  • 更具体地说:2.4.1 :001 > Question.create(title:"test", description:"this is a description with more than 10 symbols") (0.3ms) BEGIN (3.1 ms) ROLLBACK => # 2.4.1 :002 >
  • 你需要运行Question.create(title:"test", description:"this is a description with more than 10 signs", user: User.first)。问题belongs_to :user,这个关联是默认验证的
  • 啊,当然,谢谢!!好的,使用该命令我可以很好地创建问题....还有什么我可以尝试的想法吗?
【解决方案2】:

我在您的帮助下修复了它。我需要做的是:

  1. 完全删除并重建我的本地数据库
  2. 再次添加两个迁移,将用户添加到问题和答案中,因为由于某种原因重置没有这样做
  3. 删除 Heroku 应用并重新部署

现在它正在工作。无论如何,如果您想查看它,请提供完成的应用程序的链接:https://rubyoncrack.herokuapp.com/

【讨论】:

  • 这个应用太棒了! :)
  • 非常感谢!那会让我笑很久。谢谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-14
相关资源
最近更新 更多