2010-04-30 74 views
20

我在对象上使用了to_json方法,并试图让:methods参数起作用。我在我的模型(Drop)上有一个名为is_favorited_by_user?的方法。此方法采用current_user的参数,然后检查用户是否倾向于放弃该放置。我如何通过to_json方法传递这个参数。Ruby to_json:方法参数

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

回答

36

您可以添加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?) 
+0

工作!谢谢,Voyta! – 2010-04-30 16:01:31

+4

当我在索引操作中执行render:json => Drop.all时,如何扩展此解决方案。我在哪里分配current_user? – 2011-06-01 16:34:41

+3

模型中的'cattr_accessor:current_user'然后控制器中的'Model.current_user = current_user'。 – 2013-06-01 19:39:03

4

方法to_json需要的并非是带参数的,但只是“消气”的方法。 (通常情况下,那些创建基于你的数据库的属性。)

见的例子在这里,没有传递参数:

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

如果你想要做的事的习惯,你需要创建一个方法建立您想要的信息的散列,然后将该散列转换为json。

+1

有没有一种方法,我可以在我的模型中得到CURRENT_USER变量之前设置它,所以我并不需要通过论证? – 2010-04-30 15:35:06

+0

@JamesFinley模型不(也不应该)知道控制器或http请求的状态。 current_user是请求的一部分,由于上述多线程问题,不应以全局方式暴露给模型。它只应作为方法参数传递。 – hammady 2016-10-19 07:39:12