Ruby to_json:方法参数

Jam*_*ley 26 ruby-on-rails render-to-response

to_json在一个对象上使用该方法,并试图让:methods参数工作.我的模型(Drop)上有一个方法叫做is_favorited_by_user?.此方法接受一个参数current_user,然后检查用户是否收到了drop.如何通过该to_json方法传递此参数.

render :json => @drops.to_json(:methods => :is_favorited_by_user?(current_user))
Run Code Online (Sandbox Code Playgroud)

Voy*_*yta 46

您可以current_user向模型添加属性并在执行之前进行设置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?)
Run Code Online (Sandbox Code Playgroud)

  • 在进行渲染时如何扩展此解决方案:json => Drop.all在索引操作中.我在哪里分配current_user? (4认同)
  • 如果您的环境是多线程的,则将模型分配给类属性将不起作用.您可能正在将某些内容转换为JSON,然后current_user突然发生变化,现在您的JSON的一半用于一个用户,一半用于另一个用户. (4认同)
  • 模型中的cattr_accessor:current_user`,然后是控制器中的`Model.current_user = current_user`. (3认同)