# How to assign currently logged in user name to a table field

**URL:** <https://www.ruby-forum.com/t/how-to-assign-currently-logged-in-user-name-to-a-table-field/186076>\
**Category:** Rails\
**Created:** [March 31, 2010, 9:52am UTC](https://www.ruby-forum.com/t/how-to-assign-currently-logged-in-user-name-to-a-table-field/186076 "2010-03-31T09:52:23Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![railsquestion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a88e57/32.png) [@railsquestion](https://www.ruby-forum.com/u/railsquestion)\
**Post date:** [March 31, 2010, 9:52am UTC](https://www.ruby-forum.com/t/how-to-assign-currently-logged-in-user-name-to-a-table-field/186076/1 "2010-03-31T09:52:23Z")

</div>

I have 3 tables  
items (columns are: id, name , type)  
history(columns are: id, date, username, item\_id, user\_id)  
user(id , username, password)

When a user “ABC” logs in and creates a new item, a history record gets  
created with the following after\_create filter.  
How to set the username field in history table to “ABC”.

class Item \< ActiveRecord::Base  
has\_many :histories  
after\_create :update\_history  
def update\_history  
histories.create(:date=\>Time.now, username=\> ?)  
end

My login method in user\_controller  
def login  
if request.post?  
user=User.authenticate(params[:username])  
if user  
session[:user\_id] =user.id  
redirect\_to( :action=\>‘home’)  
flash[:message] = "Successfully logged in "  
else  
flash[:notice] = “Incorrect user/password combination”  
redirect\_to(:action=\>“login”)  
end  
end  
end

I am not using any authentication plugin. I would appreciate if someone  
could tell me how to achieve this without using plugin(like userstamp  
etc.) if possible.

---

<div class="post-metadata">

**Author:** ![railsquestion](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/r/a88e57/32.png) [@railsquestion](https://www.ruby-forum.com/u/railsquestion)\
**Post date:** [March 31, 2010, 2:17pm UTC](https://www.ruby-forum.com/t/how-to-assign-currently-logged-in-user-name-to-a-table-field/186076/2 "2010-03-31T14:17:40Z")

</div>

Hi,  
If u dont want to use any of the plugin then u need to write ur own  
action and need to do manually.

Like:

def current\_user  
@current\_user = User.find(session[:user\_id])  
end

Keep this action into ur application controller, It will return u the  
current logedin user object.  
So u may use this like

def update\_history  
histories.create(:date=\>Time.now, username=\> current\_user.name)  
end

I hope it will work 4 u.  
But instead of doing manually I suggest u must use Authlogic gem/plugin  
it will gives u other benefits also.
