Accessing controllers from models

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

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. [email protected]

unknown wrote:

current_user.widgets.build( params[:widget] )

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

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs