# Accessing controllers from models

**URL:** <https://www.ruby-forum.com/t/accessing-controllers-from-models/113557>\
**Category:** Rails\
**Created:** [September 1, 2007, 7:17pm UTC](https://www.ruby-forum.com/t/accessing-controllers-from-models/113557 "2007-09-01T19:17:42Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![ahmad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ahmad](https://www.ruby-forum.com/u/ahmad)\
**Post date:** [September 1, 2007, 7:17pm UTC](https://www.ruby-forum.com/t/accessing-controllers-from-models/113557/1 "2007-09-01T19:17:42Z")

</div>

Hello,

In my controllers, I have a method called ‘current\_user’. I want to make  
it automatic that when a new ActiveRecord object is created and saved  
the current user id in the current controller is saved with the object  
in the special fields called created\_by.

So far, I can’t even find a way to access the current controller from  
any model. I know that this approach makes some people uncomfortable,  
but I want to try it anyway.

–AHH

---

<div class="post-metadata">

**Author:** ![ahmad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ahmad](https://www.ruby-forum.com/u/ahmad)\
**Post date:** [September 1, 2007, 7:26pm UTC](https://www.ruby-forum.com/t/accessing-controllers-from-models/113557/2 "2007-09-01T19:26:34Z")

</div>

user\_stamp plugin does this so you could check it out. But…

In general, giving your model access to session information (like  
current\_user) is a big no-no because it breaks MVC and can cause  
issues downline. I’ve never used user\_stamp because it’s easy enough  
to use the scoping provided by AR like:

current\_user.widgets.build( params[:widget] )

in place of Widget.new( params[:widget] )

In your case, all you need is:

class Widget \< ActiveRecord::Base

belongs\_to :user, :foreign\_key =\> ‘created\_by’

[…]

end

and a similar has\_many in the User model and you can use all syntactic  
sugar that AR provides on associations.

Rein

On Sep 1, 12:17 pm, Ahmad A. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)

---

<div class="post-metadata">

**Author:** ![ahmad](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/a/a4c791/32.png) [@ahmad](https://www.ruby-forum.com/u/ahmad)\
**Post date:** [September 1, 2007, 7:33pm UTC](https://www.ruby-forum.com/t/accessing-controllers-from-models/113557/3 "2007-09-01T19:33:04Z")

</div>

unknown wrote:

> current\_user.widgets.build( params[:widget] )

I cannot believe I didn’t see that. This is a much better solution.  
Thank you!
