The user owns this and that

In most any community-based website, your users are creating objects. And sometimes, you’d only like to display them when they’re owned by the user. Usually, it’s easy enough to do the check based on the association in the template views.



"story"

However, for the sake of perhaps over-reaching, but something more readable, we try:


class Story < ActiveRecord::Base
belongs_to :account

def owned_by?(user)
self.account == user
end
end



"story"

But this gets to suck, because you have duplicate code in different classes that are just slightly different due to association names. One way to solve it is to put it in a module, and include it in different classes. After all, that’s what mixins are for.


module Ownership
def owned_by?(user)
self.account == user
end
end

class Story < ActiveRecord::Base
include Ownership
belongs_to :account
# blah blah blah
end

class Post < ActiveRecord::Base
include Ownership
belongs_to :account
end

Or alternatively, you can put it in the account, but in reverse. But now, you have to search through the associations of the owned ActiveRecord object.


class Account < ActiveRecord::Base
def owns?(ar_object)
ar_object.class.reflect_on_all_associations(:belongs_to).detect { |assoc|
ar_object.send(assoc.name) == self
} ? true : false
end
end

I find the tertiary operator to be kinda ugly there, but it doesn’t make sense to return the reflection object. Regardless, this lets you do:



"story"

However, this doesn’t work for self-associated AR objects, or objects that have two or more belongs_to to the same account. It relies on a unique belongs_to association for every object belonging to account. I’m not sure yet, which way’s the better way to go, and in the end it probably doesn’t matter as much, but I do like being able to say user.owns?(anything) for any object without really thinking about what the associations are. half-tip.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s