Rails:User.Create通过params失败

时间:2015-02-21 18:06:52

标签: ruby-on-rails params

用户控制器

从我的表单提交时,它只返回到返回页面的注册,因为.save总是失败。

 def show
    @user = User.find(params[:id])
 end
 def new
     @user = User.new
 end

 def create
    @user = User.new user_params
    if @user.save
         redirect_to @user
    else
        render 'new'
    end
end

    def user_params
        params.require(:user).permit(:username, :email, :password, :password_confirmation)
    end
end

我试过这个,但我得到了ActiveModel :: ForbiddenAttributesError

def create
@user = User.new(params[:user])
if @user.save
redirect_to @user
else
render 'new'
end
end

Schema.rb

 ActiveRecord::Schema.define(version: 20150215194936) do

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

  add_index "users", ["email"], name: "index_users_on_email", unique: true

end

的Gemfile

source 'https://rubygems.org'

gem 'rails', '4.2.0'
gem 'bootstrap-sass'
gem 'bcrypt-ruby'
gem 'faker'
gem 'will_paginate'
gem 'bootstrap-will_paginate'
gem 'jquery-rails'
gem 'turbolinks'

group :development, :test do
  gem 'sqlite3'
  gem 'rspec-rails'
  gem 'guard-rspec'
  gem 'guard-spork'
  gem 'childprocess'
  gem 'spork', '0.9.2'
end

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails'
  gem 'coffee-rails'
  gem 'uglifier'
end

group :test do
  gem 'capybara'
  gem 'factory_girl_rails'
  gem 'cucumber-rails', :require => false
  gem 'database_cleaner'
  # gem 'launchy'
  # gem 'rb-fsevent', :require => false
  # gem 'growl'
end

group :production do
  gem 'pg'
end

1 个答案:

答案 0 :(得分:1)

你应该修改这一行:

params.require(:user)
      .permit(:name, :email, :password, :password_confirmation)

您的模型的字段为:name,但您使用的是:username