【问题标题】:Rails Migration File not adding columns to Mysql databaseRails 迁移文件未向 Mysql 数据库添加列
【发布时间】:2017-08-10 20:46:27
【问题描述】:

我正在尝试在 Rails 中创建一个登录系统,但是,当我进入注册页面时,我收到一条错误消息:“undefined method `first_name' for #”。我检查了用户数据库中的“first_name”列,发现“users”表中仅有的列是“id”、“created_at”和“updated_at”。我使用 rails new appname -d mysql 创建了我的应用程序,我有 mysql2 gem,我更新了我的 databases.yml 文件,并且我已经运行了“rake db:migrate”。不过,没有任何效果。我怎样才能解决这个问题?这是我的用户控制器:

   class UsersController < ApplicationController
  def new
    @user = User.new
  end
  def create 
    @user = User.new(user_params) 
  if @user.save 
    session[:user_id] = @user.id 
    redirect_to '/login' 
  else 
    redirect_to '/signup' 
  end 
end
  private
  def user_params
    params.require(:user).permit(:first_name, :last_name, :email, :password)
  end
end

这是我的路由器:

Rails.application.routes.draw do
    root 'main#index'
    get '/login' => 'sessions#new'
    get '/signup' => 'users#new'
    resources :users
    post 'login' => 'sessions#create'
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

这是我的模型:

   class User < ApplicationRecord
        has_secure_password
    end

这是我的迁移文件:

class CreateUsers < ActiveRecord::Migration[5.0]
  def change
    create_table :users do |t|
      t.string :first_name
      t.string :last_name
      t.string :email
      t.string :password_digest

      t.timestamps
    end
  end
end

这是我的看法:

<div class="login">
  <div class="container">
    <div class="form">

    <h1>Sign up</h1>

    <%= form_for(@user) do |f| %>
      <%= f.text_field :first_name, :placeholder => "First name" %>
      <%= f.text_field :last_name, :placeholder => "Last name" %>
      <%= f.email_field :email, :placeholder => "Email" %>
      <%= f.password_field :password, :placeholder => "Password" %>
      <%= f.submit "Create an account", class: "btn-submit" %>
    <% end %>


    </div>
  </div>
</div> 

我在 Ubuntu 16.04 上使用 Rails 5.0.2

【问题讨论】:

  • 你能不能尝试重新迁移(db:migrate:redo) 上次迁移
  • 我试过了,它奏效了。谢谢!

标签: mysql ruby-on-rails ruby


【解决方案1】:

您可能想尝试使用 db:migrate:redo 重做迁移,如果这不起作用,请创建一个新的迁移添加相应的列。

  class CreateUsers < ActiveRecord::Migration[5.0]
     def change
        add_column :products, :part_number, :string
        add_column :products, :price, :decimal
     end
  end

【讨论】:

    猜你喜欢
    • 2010-12-08
    • 2014-12-25
    • 2016-08-02
    • 1970-01-01
    • 1970-01-01
    • 2021-01-01
    • 2013-05-31
    • 2011-06-17
    • 1970-01-01
    相关资源
    最近更新 更多