2017-03-19 39 views
0

我想在Rails中创建一个登录系统,但是当我进入注册页面时,出现错误:“未定义的方法`first_name'for#”。我检查了我的用户数据库中的“first_name”列,发现“users”表中唯一的列是“id”,“created_at”和“updated_at”。我创建我的应用程序使用rails new appname -d mysql,我有mysql2 gem,我更新了我的databases.yml文件,并且运行了“rake db:migrate”。但是,没有任何工作。我怎样才能解决这个问题?这是我的用户控制器:Rails迁移文件不向Mysql数据库添加列

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> 

我用Rails 5.0.2在Ubuntu 16.04

+0

你可以尝试重新迁移(db:migrate:redo)最后一次迁移 –

+1

我试过了,它工作。谢谢! –

回答

0

你可能要尝试重新与数据库迁移:迁移:重做,如果不工作,创建一个新的迁移将各列。

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