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_password"
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
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..
If you cannot redo your migration, use change_column_default like