Ruby to_json :methods arguments

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 04:27:21

问题


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

回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2745607/ruby-to-json-methods-arguments

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!