Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby to_json :methods arguments

I am using the to_json method on an object, and trying to get the :methods argument to work. I have a method on my model (Drop) called is_favorited_by_user?. This method takes an argument of the current_user, and then checks to see if the drop is favorited by the user. How can I pass this argument through the to_json method.

render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user)) 
like image 850
James Finley Avatar asked Apr 30 '10 15:04

James Finley


1 Answers

You can add current_user attribute to your model and set it before executing to_json

  attr_accessor :current_user    def is_favorited_by_user?(user=nil)     user ||= current_user     # rest of your code   end   @drops.current_user = current_user render :json => @drops.to_json(:methods => :is_favorited_by_user?) 
like image 193
Voyta Avatar answered Sep 18 '22 23:09

Voyta