开发者

Ruby to_json :methods arguments

开发者 https://www.devze.com 2022-12-28 23:00 出处:网络
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 curre

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开发者_Python百科 this argument through the to_json method.

render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user))


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?)


The methods to_json takes aren't intended to be ones that take arguments, but just "getter" methods. (Typically the ones created based on your db attributes.)

See examples here, none pass arguments:

http://apidock.com/rails/ActiveRecord/Serialization/to_json

If you want to do something custom, you'll need to create a method that builds up the hash of info you want, then convert that hash to json.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号