issues with model in ruby on rails

8 views
Skip to first unread message

amvis

unread,
Apr 3, 2012, 4:12:46 AM4/3/12
to rubyonra...@googlegroups.com
class SystemAdmin < ActiveRecord::Base
  belongs_to :user
end

class User < ActiveRecord::Base
  has_secure_password
  
  has_one  :system_admin  
end

@user = User.find_by_user_name(user_name)
              if !@user.system_admins.nil?
                 puts 'am a sys_admin'

The above code gives error like this

NoMethodError (undefined method `system_admins' for #<User:0xa81a2e0>):
  app/controllers/application_controller.rb:17:in `user_authenticate'

Have any problem with this condition checking  if !@user.system_admins.nil? also any problem with the model relation?



Thank you
vishnu

                

Michael Pavling

unread,
Apr 3, 2012, 4:20:50 AM4/3/12
to rubyonra...@googlegroups.com
On 3 April 2012 09:12, amvis <vgrkr...@gmail.com> wrote:
> class User < ActiveRecord::Base

>   has_one  :system_admin
> end
>
> @user = User.find_by_user_name(user_name)
>               if !@user.system_admins.nil?
>                  puts 'am a sys_admin'
>
> The above code gives error

Since you've defined the association as a has_one, you should use it
in the singular:
if !@user.system_admin.nil?

but "!...nil?" is a bit stinky; either use:
if @user.system_admin
or
unless @user.system_admins.nil?

amvis

unread,
Apr 3, 2012, 4:31:21 AM4/3/12
to rubyonra...@googlegroups.com
Thanks, got the solution...
Reply all
Reply to author
Forward
0 new messages