DavideCariani
DavideCariani

Reputation: 273

helper method to check if a record is owned by the current user in rails

i'm bulding a rails 3 app, i'm using devise for manage the auth logics but i was wonder if there is a helper method to check if the current user owns an object (a record into db) that has an association "has_many".

example:

User

has_many :reports 

i have this situation:

<%=  current_user.id == report.user.id ? "Personal Report" : report.user.username %>

is possible to create something like:

<%= owned ? "yes" : "no" %>

thanks

Upvotes: 2

Views: 3181

Answers (2)

MrYoshiji
MrYoshiji

Reputation: 54882

You could define this method in your Report model:

Model restricted:

class Report < ActiveRecord::Base

  def owned_by?(user)
    self.user_id == (user.try(:id) || user)
  end

And then use it like this:

<%= report.owned_by?(current_user) ? 'yes' : 'no' %>

This owned_by?(user) method accepts both a User object AND an Integer (user_id).

Generic method for each model that has an association with User:

A helper method would do the trick:

module OwnerHelper
  def is_owner?(object)
    return nil if(current_user.nil? || !object.respond_to(:user_id))
    current_user.try(:id) == object.try(:user_id)
  end
end

This helper will return true if current_user is owner, false if not and nil if current_user is nil OR the object has no user_id attribute.

Upvotes: 6

Rahul garg
Rahul garg

Reputation: 9362

Helper:

def owned(report)
    current_user.id == report.user_id
end

Usage:

<%= owned(report) ? "yes" : "no" %>

Upvotes: 13

Related Questions