in UsersController#create, User.new(params[:user]) return an empty User (params looks good)

删除回忆录丶 提交于 2019-12-11 15:25:42

问题


I'm kind of new to Rails 3.1. and I'm facing an issue only in my production env with my Signup form (actually, it's more about the controller).

Here is the code in User

class UsersController < ApplicationController

[...]

def create
  @user = User.new(params[:user])
  logger.info "value of login in param : #{params[:user][:login]}" #-> log the actual login
  logger.info "value of login : #{@user.login}"                    #-> log empty
  @user.admin = false
  if @user.save
    flash[:notice] = t('flash.notice.user.create.valid')
    redirect_back_or_default root_path
  else
    flash[:notice] = t('flash.notice.user.create.invalid')
    render :action => :new
  end
 end
end

Also, the controller logs show that the params hash is good

Parameters: {"utf8"=>"✓",
  "authenticity_token"=>"QwOqmp0CT/d4mmC1yiLT4uZjP9bNDhbUXHanCQy5ZrA=", 
  "user"=>{"login"=>"myLogin", 
           "email"=>"t.r@gmail.com", 
           "password"=>"[FILTERED]", 
           "password_confirmation"=>"[FILTERED]"}}

My login form works as expected (already created users are able to sign in)

Again, this only happens in production.

EDIT: Here is my User Model

class User < ActiveRecord::Base
  acts_as_authentic

  #== Callbacks
  before_create :set_defaults

  attr_accessible :avatar     ##### EDIT: TO FIX THE ISSUE, ADD THE OTHER FIELDS AS WELL

  protected

  def set_defaults
    self.total_1 = self.total_2 = self.total_3 = 0
  end
end

回答1:


Just to memorialize the answer from the comments above:

Normally you can use mass assignment to set fields on a model, but when you use attr_accessible, you are then limited to only mass assigning those fields. So stuff like User.new(params[:user]) won't work; instead, you'd have to do:

@user = User.new
@user.login = params[:user][:login]
# ...etc.
@user.save

Simple add your fields to the attr_accessible list and you can go back to mass assignment.



来源:https://stackoverflow.com/questions/8024343/in-userscontrollercreate-user-newparamsuser-return-an-empty-user-params

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!