Re: Accessing Models from Modules: what am I missing?

Jarkko Laine
2005-03-22T09:28:18Z

On 22.3.2005, at 06:38, David Adams wrote:

> I''ve been playing around with Ruby and Rails for a couple of
months
> now.  I''m trying to develop a module/gem that will provide some
> functionality on top of a given database setup.  As such, I''m
trying
> to call an ActiveRecord Model from within the module code (which is
> then mixed into a Rails controller).  However, apparently, code in the
> module can''t see/create objects that can been seen/created
directly in
> the Controller.

You have to suck in the user class file. Put:

require ''user''

in the beginning of the module file.

//jarkko

>
> Here''s some (untested) sample code to get a feel for what
I''m trying
> to do:
>
> module AddOn
>   def create_user(username)
>     u = User.new
>     u.username = username
>     u.save
>   end
> end
>
> class User < ActiveRecord::Base
> end
>
> class TestController < ApplicationController
>   include AddOn
>
>   def create
>     create_user(''jsmith'')
>     render_text ''done!''
>   end
> end
>
> Start WEBRick and visit /test/create and I get a NameError:
> uninitialized constant AddOn::User.
>
> So maybe this is more of a generic Ruby question, and please call me
> out if this is out of line for this list.  Thanks!
>
> David Adams
> _______________________________________________
> Rails mailing list
> Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
--
Jarkko Laine
http://jlaine.net
http://odesign.fi


_______________________________________________
Rails mailing list
Rails-1W37MKcQCpIf0INCOvqR/iCwEArCW2h5@public.gmane.org