0

I have a column 'created_by' in a table. Based on the role of logged in user I have to show either the id of the user or the role of the user. Suppose the id logged in user is a customer and the record was created by the user who has support role, then it should show 'Support', and if the support logs in then show the id of the person who added(even if its a different support person's id). I can figure out the current user's role. How can I achieve this without defining a separate apis based on role? Is it possible to have same api to get results from db based on query but transform the column based on role.

user3075906
  • 725
  • 1
  • 8
  • 19

1 Answers1

1

My initial thought is to create a view helper.

I'll give you an idea for what it could look like. Since you didn't share the name of the model in your question, I'm picking an arbitrary model (Watermelons) that has a created_by relationship to Users. I realize that's a silly choice. I'm an enigma...

app/helpers/watermelons_helper.rb

module WatermelonsHelper
  def created_by_based_on_role(watermelon)
    if current_user.role == "Support" || watermelon.created_by.role == "Generic User"
      watermelon.created_by.name
    else 
      "The Watermelons.com Support Team"
    end
  end
end

app/controllers/watermelons_controller.rb

class WatermelonsController < Application Controller
  def show
    @watermelon = Watermelon.find(params[:watermelon_id])
  end
end

app/views/watermelons/show.html.erb

...
<p>This watermelon was created by <%= created_by_based_on_role(@watermelon) %></p>
...

The reason why I'd make this a helper method and not a method in the watermelon.rb model is that the method is dependent on the current_user, which the model can't explicitly know each time (assuming you're using Devise or a hand-rolled, Hartl-style current_user helper method as well).

Edit: Per feedback, let's make it a model method...

app/models/watermelons.rb

class Watermelon < ActiveRecord::Base
  ...
  def created_by_based_on_role(viewing_user)
    if viewing_user.role == "Support" || self.created_by.role == "Generic User"
      self.created_by.name
    else 
      "The Watermelons.com Support Team"
    end
  end
  ...
end

Note that I'm implementing this as an instance method, which means you will need to call "watermelon.created_by_based_on_role(current_user)" in the controller or view.

Lanny Bose
  • 1,811
  • 1
  • 11
  • 16
  • Thanks. But I need to do it in model itself. Our ui gets all data from backend using rest apis and will just display what it got without doing any transformation based on roles. Backend only has to check the role and do the transformation. – user3075906 Jun 05 '15 at 15:52