Find account name

230 views
Skip to first unread message

Leonel *.*

unread,
Oct 13, 2010, 4:05:46 PM10/13/10
to rubyonra...@googlegroups.com
I have an accounts table
ACCOUNTS
id
company_name

and a users table
USERS
id
username
password
account_id

I want a page where I display the company_name for the user. So far, I
managed to get the user_id from the session...
<%= session[:user_id] %>

Now, I guess I can use the user_id, to find it's account_id, and then
match the account_id and get the company_name.

I don't know, maybe I'm overcomplicating things. I just managed to get
the user_id and I'm now stuck.

--
Posted via http://www.ruby-forum.com/.

Colin Law

unread,
Oct 13, 2010, 4:13:58 PM10/13/10
to rubyonra...@googlegroups.com
On 13 October 2010 21:05, Leonel *.* <li...@ruby-forum.com> wrote:
> I have an accounts table
> ACCOUNTS
> id
> company_name
>
> and a users table
> USERS
> id
> username
> password
> account_id
>
> I want a page where I display the company_name for the user. So far, I
> managed to get the user_id from the session...
> <%= session[:user_id] %>
>
> Now, I guess I can use the user_id, to find it's account_id, and then
> match the account_id and get the company_name.

If you have a user in current_user for example then the company is
current_user.company, so the name is current_user.company.name. Such
is the magic of Rails. Watch out for the cas when the user does not
have a company, in which current_user.company will be nil. Check out
the rails guide on ActiveRecord relationships to see how this all
works.

Colin

>
> I don't know, maybe I'm overcomplicating things. I just managed to get
> the user_id and I'm now stuck.
>
> --
> Posted via http://www.ruby-forum.com/.
>

> --
> You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
> To post to this group, send email to rubyonra...@googlegroups.com.
> To unsubscribe from this group, send email to rubyonrails-ta...@googlegroups.com.
> For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.
>
>

Leonel *.*

unread,
Oct 13, 2010, 4:33:11 PM10/13/10
to rubyonra...@googlegroups.com
> If you have a user in current_user for example then the company is
> current_user.company, so the name is current_user.company.name. Such
> is the magic of Rails. Watch out for the cas when the user does not
> have a company, in which current_user.company will be nil. Check out
> the rails guide on ActiveRecord relationships to see how this all
> works.

Thanks! This is what I did...

CONTROLLER
current_user_id = session[:user_id]
@current_user = User.find(current_user_id)

TEMPLATE
<h2><%= @current_user.account.name %></h2>

Seems soo simple but it's not to us newbies.

Leonel *.*

unread,
Oct 13, 2010, 4:34:28 PM10/13/10
to rubyonra...@googlegroups.com
Simplified it even more...

CONTROLLER
@current_user = User.find(session[:user_id])

TEMPLATE
<h2><%= @current_user.account.name %></h2>

--
Posted via http://www.ruby-forum.com/.

Leonel *.*

unread,
Oct 13, 2010, 4:42:45 PM10/13/10
to rubyonra...@googlegroups.com
Simplified it even moreeeee for the designer...

CONTROLLER
@company_name = User.find(session[:user_id]).account.name

TEMPLATE
<h2><%= @company_name %></h2>

Colin Law

unread,
Oct 13, 2010, 5:05:43 PM10/13/10
to rubyonra...@googlegroups.com
On 13 October 2010 21:42, Leonel *.* <li...@ruby-forum.com> wrote:
> Simplified it even moreeeee for the designer...
>
> CONTROLLER
> @company_name = User.find(session[:user_id]).account.name

OK, but did you take heed of my warning in my first reply? Can you
guarantee that a user will always have a company (even in unusual
circumstances)? Add into your automated tests one where the user does
not have a company and see what happens. (Hint, find returns nil if
it cannot find what you are asking for).

Another point, it might be worth providing a method somewhere called
current_user (possibly in application_controller) that does the find,
then you will not need to keep typing the find everywhere you want
current_user.

Colin

Leonel *.*

unread,
Oct 13, 2010, 5:54:26 PM10/13/10
to rubyonra...@googlegroups.com
> OK, but did you take heed of my warning in my first reply? Can you
> guarantee that a user will always have a company (even in unusual
> circumstances)? Add into your automated tests one where the user does
> not have a company and see what happens. (Hint, find returns nil if
> it cannot find what you are asking for).

Every time an user is created, the account_id is recorded on its row
too. But sure it's good to have a safety net.

> Another point, it might be worth providing a method somewhere called
> current_user (possibly in application_controller) that does the find,
> then you will not need to keep typing the find everywhere you want
> current_user.

Aight! DRYer and DRYer

Leonel *.*

unread,
Oct 14, 2010, 11:32:34 AM10/14/10
to rubyonra...@googlegroups.com
> Another point, it might be worth providing a method somewhere called
> current_user (possibly in application_controller) that does the find,
> then you will not need to keep typing the find everywhere you want
> current_user.

I'm trying to do exactly that, but the app doesn't seem to find the
session if placed on the application controller.

ACCOUNTS_CONTROLLER (works fine)
User.find(session[:user_id]).account.name

APPLICATION_CONTROLLER (error!)
User.find(session[:user_id]).account.name

ERROR
Couldn't find User without an ID

Leonel *.*

unread,
Oct 14, 2010, 11:44:09 AM10/14/10
to rubyonra...@googlegroups.com
Found something very weird, the log trace reads...


EPRECATION WARNING: Disabling sessions for a single controller has been
deprecated. Sessions are now lazy loaded. So if you don't access them,
consider them off. You can still modify the session cookie options with
request.session_options. (called from
[..]/app/controllers/application_controller.rb:6)

Colin Law

unread,
Oct 14, 2010, 11:45:54 AM10/14/10
to rubyonra...@googlegroups.com

Can you show us the code around the error and how you are calling it?

Colin

Leonel *.*

unread,
Oct 14, 2010, 11:50:37 AM10/14/10
to rubyonra...@googlegroups.com
Ok, so I made this change: I used find_by_id instead of just find.

APPLICATION CONTROLLER
@company_id = User.find_by_id(session[:user_id]).account.id

ERROR
Routing Error
undefined method `account' for nil:NilClass

I'm not good at routing, but will read about it right now. If you got a
suggestion is very much welcomed.

Leonel *.*

unread,
Oct 14, 2010, 12:01:27 PM10/14/10
to rubyonra...@googlegroups.com
Colin Law wrote in post #950191:

mmm... I think I need some tweaking on the routes file. This is all the
code in my application controller

class ApplicationController < ActionController::Base
before_filter :authorize

protect_from_forgery

@company_name = User.find(session[:user_id]).account.name

protected

def authorize
unless User.find_by_id(session[:user_id])
redirect_to login_url, :notice => "Please log in"
end
end

end

Edmond Kachale

unread,
Oct 14, 2010, 12:06:50 PM10/14/10
to rubyonrails-talk


2010/10/14 Leonel *.* <li...@ruby-forum.com>

Ok, so I made this change: I used find_by_id instead of just find.

APPLICATION CONTROLLER
@company_id = User.find_by_id(session[:user_id]).account.id

ERROR
Routing Error
undefined method `account' for nil:NilClass

I'm not good at routing, but will read about it right now. If you got a
suggestion is very much welcomed.


You might be searching for a user before a session is established, as such the session[:user_id] is nil. You may need to revise the position of this statement: @company_id = User.find_by_id(session[:user_id]).account.id in your application_controller. Remember that often the application controller the first to load even when you are just open your application. You may need to add a condition. Something like:
@company_id = User.find_by_id(session[:user_id]).account.id if session[:user_id]

A General Note:

Personally, I would not recommend writing User.find_by_id(session[:user_id]).account.id although Rails natually allows for this short cut. For testing sake (or whether you call it bug hunt), I would find the user first and search for the user's account. In that way I will be able to test for the avaliabilty of the user and the availability of the account separately. I should say, despite that "every time an user is created, the account_id is recorded on its row too", bugs are are bugs, they always bug. Anything can happen midway. So consider revising that statement. This is a personal preference, based on my experience. It is subject to comments and criticisms.

Happy coding.

---
Edmond
Software Developer | Baobab Health Trust (http://www.baobabhealth.org/) | Malawi

Cell:  +265 999 465 137 | +265 881 234 717

"Leading the Improvement of Health through Information and Communication Technology in the Developing World" The Creed of Baobab Health
 

Leonel *.*

unread,
Oct 14, 2010, 12:27:44 PM10/14/10
to rubyonra...@googlegroups.com
> For testing sake (or whether you call it bug hunt),
> I would find the user first and search for the user's account. In that way
> I will be able to test for the avaliabilty of the user and the
> availability of the account separately.

Thanks, ok, so I did this...

APPLICATION CONTROLLER


class ApplicationController < ActionController::Base
before_filter :authorize

protect_from_forgery

@user_id = User.find_by_id(session[:user_id])
@account_id = @user_id.account.id

protected

def authorize
unless User.find_by_id(session[:user_id])
redirect_to login_url, :notice => "Please log in"
end
end

end

ERROR


Routing Error
undefined method `account' for nil:NilClass

Like the error reads, I think I need to do something on the routes file.
I'm not sure what 'cause I'm a newbie but I'm searching for the answer.

Colin Law

unread,
Oct 14, 2010, 12:53:56 PM10/14/10
to rubyonra...@googlegroups.com
On 14 October 2010 17:27, Leonel *.* <li...@ruby-forum.com> wrote:
>> For testing sake (or whether you call it bug hunt),
>> I would find the user first and search for the user's account. In that way
>> I will be able to test for the avaliabilty of the user and the
>> availability of the account separately.
>
> Thanks, ok, so I did this...
>
> APPLICATION CONTROLLER
> class ApplicationController < ActionController::Base
>  before_filter :authorize
>
>  protect_from_forgery
>
>  @user_id = User.find_by_id(session[:user_id])
>  @account_id = @user_id.account.id

Doing it like that means that it will get executed when the controller
loads, which in production will be only once. You need to put it in a
method of application_controller then call it from your code when you
want to know the result.

Are you using authlogic? If so I am sure the examples of how to use
it include how to do a current_user method.

Colin

Leonel *.*

unread,
Oct 14, 2010, 5:54:26 PM10/14/10
to rubyonra...@googlegroups.com
Colin Law wrote in post #950219:

So you mean doing something like this in the application controller?
def current_user
User.find_by_id(session[:user_id])
end

I use the user id, the account id, the account name and the account id
in several parts of the application. Everytime I need to access the data
I have to add something like this on each controller method...

class AccountsController < ApplicationController
# GET /accounts
# GET /accounts.xml
def index
@accounts = Account.all

@company_id = User.find(session[:user_id]).account.id


@company_name = User.find(session[:user_id]).account.name

@company_address_one =
User.find(session[:user_id]).account.address_one
@company_address_two =
User.find(session[:user_id]).account.address_two
@company_city = User.find(session[:user_id]).account.city
@company_state = User.find(session[:user_id]).account.state
@company_zip = User.find(session[:user_id]).account.zip
@company_web_address =
User.find(session[:user_id]).account.web_address
@company_phone_number_office =
User.find(session[:user_id]).account.phone_number_office
@company_phone_number_fax =
User.find(session[:user_id]).account.phone_number_fax

How can I make the company name available to all views with something
like this... @company_name

Marnen Laibow-Koser

unread,
Oct 14, 2010, 10:33:07 PM10/14/10
to rubyonra...@googlegroups.com
Leonel *.* wrote in post #950292:
[...]

> So you mean doing something like this in the application controller?
> def current_user
> User.find_by_id(session[:user_id])
> end
>

That's usually sensible.

> I use the user id, the account id, the account name and the account id
> in several parts of the application. Everytime I need to access the data
> I have to add something like this on each controller method...
>
> class AccountsController < ApplicationController
> # GET /accounts
> # GET /accounts.xml
> def index
> @accounts = Account.all
>
> @company_id = User.find(session[:user_id]).account.id
> @company_name = User.find(session[:user_id]).account.name
> @company_address_one =
> User.find(session[:user_id]).account.address_one
> @company_address_two =
> User.find(session[:user_id]).account.address_two
> @company_city = User.find(session[:user_id]).account.city
> @company_state = User.find(session[:user_id]).account.state
> @company_zip = User.find(session[:user_id]).account.zip
> @company_web_address =
> User.find(session[:user_id]).account.web_address
> @company_phone_number_office =
> User.find(session[:user_id]).account.phone_number_office
> @company_phone_number_fax =
> User.find(session[:user_id]).account.phone_number_fax
>

No, you certainly don't. Since current_user is defined in
ApplicationController, and since all your other controllers inherit from
ApplicationController, all you need in your controller is

@current_user = current_user

and then do @current_user.account.whatever in the view.

> How can I make the company name available to all views with something
> like this... @company_name

Use a before_filter or the technique I just described.

Best,
-- 
Marnen Laibow-Koser
http://www.marnen.org
mar...@marnen.org

Leonel *.*

unread,
Oct 15, 2010, 10:54:18 AM10/15/10
to rubyonra...@googlegroups.com
>> So you mean doing something like this in the application controller?
>> def current_user
>> User.find_by_id(session[:user_id])
>> end
> That's usually sensible.
>
> Since current_user is defined in
> ApplicationController, and since all your other controllers inherit from
> ApplicationController, all you need in your controller is
>
> @current_user = current_user
>
> and then do @current_user.account.whatever in the view.
>
>> How can I make the company name available to all views with something
>> like this... @company_name

I tried it, and it does work. But how can I make it work on the
APPLICATION CONTROLLER instead of on an individual controller. Several
views need the account_id, so I would have to repeat myself in several
controllers writing
@company_name = company_name

For example with this code in the application controller...

def company_id


@company_id = User.find_by_id(session[:user_id]).account.id

end
@company_id = company_id

I get this error...
Routing Error
undefined local variable or method `company_id' for
ApplicationController:Class

Leonel *.*

unread,
Oct 18, 2010, 1:02:25 PM10/18/10
to rubyonra...@googlegroups.com
Still same error...

APPLICATION CONTROLLER
@company_id = company_id
def company_id
output_id = User.find_by_id(session[:user_id]).account.id
end

ERROR


Routing Error
undefined local variable or method `company_id' for
ApplicationController:Class

Why would it say the method is undefined, if it ISSSS defined? and why
would it have something to do with the routes if it's just a simple
method and a simple variable?

Marnen Laibow-Koser

unread,
Oct 18, 2010, 1:59:50 PM10/18/10
to rubyonra...@googlegroups.com
Leonel *.* wrote in post #955184:

> Still same error...
>
> APPLICATION CONTROLLER
> @company_id = company_id
> def company_id
> output_id = User.find_by_id(session[:user_id]).account.id
> end
>
> ERROR
> Routing Error
> undefined local variable or method `company_id' for
> ApplicationController:Class
>
> Why would it say the method is undefined, if it ISSSS defined?

Obviously it wouldn't.

You're defining an instance method, and apparently trying to call it as
if it were a class method. The problem is apparently in the line
@company_id = company_id: since that's outside any method definition,
self is the ApplicationController class, not an instance. You need to
put this line inside an instance method for it to do what you want.

If this is hard to understand, review the semantic and syntactical
distinctions between class methods and instance methods in Ruby.

> and why
> would it have something to do with the routes if it's just a simple
> method and a simple variable?

I don't think it does have to do with routes.

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
mar...@marnen.org

--
Posted via http://www.ruby-forum.com/.

Leonel *.*

unread,
Oct 18, 2010, 3:02:13 PM10/18/10
to rubyonra...@googlegroups.com
I tried to simplify to find the root of the problem, but this doesn't
work either!

APPLICATION CONTROLLER
@company_id = 1;

VIEW
<%= @company_id %> returns nothing

Marnen Laibow-Koser

unread,
Oct 18, 2010, 3:05:20 PM10/18/10
to rubyonra...@googlegroups.com
Leonel *.* wrote in post #955223:

> I tried to simplify to find the root of the problem, but this doesn't
> work either!
>
> APPLICATION CONTROLLER
> @company_id = 1;

This is a class instance variable, because self is the class itself
here.

>
> VIEW
> <%= @company_id %> returns nothing

This is an instance variable.

Nearly the same problem. Please read my immediate previous post. The
study material I recommended in that one will solve this problem too.

You need to gain a better understanding of what belongs to the class and
what belongs to the instance.

Best,
--
Marnen Laibow-Koser
http://www.marnen.org
mar...@marnen.org

--
Posted via http://www.ruby-forum.com/.

Leonel *.*

unread,
Oct 18, 2010, 3:38:34 PM10/18/10
to rubyonra...@googlegroups.com
> You need to gain a better understanding of what belongs to the class and
> what belongs to the instance.
True, will do.

Although I found a different solution.

APPLICATION HELPER
def company_id
User.find_by_id(session[:user_id]).account.id
end

Edmond Kachale

unread,
Oct 22, 2010, 4:41:39 AM10/22/10
to rubyonrails-talk
Leonel,

Sorry, I have been of the line for sometime. I haven't followed this mail thread, but I had already answered your problem last Friday, so I just send it through. I hope my contribution will still be of good help.
The error means that you are accessing an "account" attribute of a nil user.

Allow me to provide a little bit of a tutorial.
==============================
Of course, I see  "protect_from_forgery" method, but let me assume that I don't see it.

In general, any code that is not in a method is generally executed as Ruby goes parses the script. As most languages do, Ruby too executes every script sequentially from top to bottom (unless there are conditions to change the order). Suppose we have the following:

statement_1

def my_method
some_code
end

statement_2
statement_3
my_method # call to my method

Then Ruby will execute statement_1, statement_2, statement_3 and the calls the method my_method. It just "skips" the method declaration (if seasoned programmers allow me to say so).

Now, in you code, I believe that at the point you are finding the User,  session[:user_id] is still null. In order to prove it, try to raise the session variable before this  @user_id = User.find_by_id(session[:user_id]). Thus try, this:

 raise "The id of the current user is #{session[:user_id]} . Hip-hop Hooray!!!"

 @user_id = User.find_by_id(session[:user_id])

If the user id exists in session[:user_id] it will be printed out. If it gets printed out, make sure that it matches the user_id you have put in session.

I haven't tested you code for this, but I hypothesize that the session[:user_id] will not be printed out.

Now, What do you need to get it right?
============================

I would suggest that the following possible idea. I notice you have before_filter: authorize.  in your authorize method after authenticating the user, put the user id in session.  Look out for consistency (session[:user_id] may not equal to session["user_id"])!!! Here is my sample code!!!!!!!!

Notice where I am initiating session[:user_id].

  def login
    session[:user_id] = nil
    if request.post?

    username = params[:user][:username]
    password = params[:user][:password]

    user = User.authenticate(username, password)
      if user
        session[:user_id] = user.id
      else
        flash[:notice] = "Invalid user/password combination"
      end
    end
  end

Now you are safe to use session[:user_id] as follows (You may place this code in the index method of your ApplicationController):

  @company_name = User.find(session[:user_id]).account.name unless (session[:user_id].empty?)

You can also take advantage of the "if user" block statement above (since it is execute if an only if the user is authenticated), find the user's account and just keep the account name in session (It might not be a good programming practice, but it can save a lot. This is just my recommendation!!).
Reply all
Reply to author
Forward
0 new messages