Initializing "new users" in Rails
I'm creating a Ruby on Rails application, and I'm trying to create/login/logout users.
This is the schema for Users
:
create_table "users", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.text "reputation"
t.integer "questions_asked"
t.integer "answers_given"
t.string "request"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email_hash"
t.string "username"
t.string "hashed_passwor开发者_高级运维d"
t.string "salt"
end
The user's personal information (username, first/last names, email) is populated through a POST. Other things such as questions_asked
, reputation
, etc. are set by the application, so should be initialized when we create new users. Right now, I'm just setting each of those manually in the create
method for UsersController
:
def create
@user = User.new(params[:user])
@user.reputation = 0
@user.questions_asked = 0
@user.answers_given = 0
@user.request = nil
...
end
Is there a more elegant/efficient way of doing this?
params[:user] is just a hash, you could create a hash and merge it with the params like
def create
params[:user].merge(
{
:reputation => 0,
:questions_asked => 0,
:answers_given => 0
...
}
)
@user = User.new(params[:user])
end
You could move this to your model if you wanted to remove that code from your controller, and just add an after_create filter..
but really if its just setting things to 0, set defaults in the database columns and you wont even have to handle it in your code..
create_table "users", :force => true do |t|
t.string "first_name"
t.string "last_name"
t.text "reputation", :default => 0
t.integer "questions_asked", :default => 0
t.integer "answers_given", :default => 0
t.string "request"
t.datetime "created_at"
t.datetime "updated_at"
t.string "email_hash"
t.string "username"
t.string "hashed_password"
t.string "salt"
end
If you cannot redo your migration, use change_column_default like
class SetDefaultsOnUsers < ActiveRecord::Migration
def self.up
change_column_default "users", "reputation", 0
end
def self.down
change_column_default "users", "reputation", default
end
end
You can use http://api.rubyonrails.org/classes/ActiveRecord/ConnectionAdapters/SchemaStatements.html#M001909
精彩评论