Reputation: 745
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.
Upvotes: 0
Views: 102
Reputation: 1857
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.
Upvotes: 1