Association extensions - has_one

Hi,

I’m struggling with something that must be very common pattern, and
want to do it the correct rails/ruby way but am a bit dense !

I have users - an admin user, registered users and a guest user (using
ModelSecurity)

For many of linked associations I want the admin to be able to list or
edit all instances, the registered user only their own one and guest
none at all.

So somehow I want to over ride or extend the associations, or find, so
that the condition is captured in one place and my controller/view
code isn’t littered with these same if, else blocks…e.g something
like…

   if(User.current.admin?)
      Theme.find(:all)
    elsif(User.current.registered?)
      User.current.theme
    else
      nil
    end

I’ve tried using the Association extensions so I can simply call
something like

@theme = User.current.theme.find_theme

e.g

class User < ActiveRecord::Base

has_one :theme do
def find_theme()
if(admin?)
Theme.find(:all)
elsif(registered?)
User.current.theme
else
[]
end
end
end

But no joy, this gives method missing. If I change the association to
has_many however, it does work - but this is obviously not then
correct with the model.

Do extensions only work for has_many ?

Any advice on best place or pattern to encapsulate this kind of
situation much appreciated.

Many thanks
tom

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