2011-09-02 53 views
1

首先,我用Rails 3.0.6和Ruby 1.9.2重写as_json方法使用参数

我有两个不同的动作控制器,都应该返回一个JSON对象,但不同的格式。因此,我重写了as_json方法以我自己的格式编写JSON对象。问题是我不知道如何将params传递给as_json方法,因为它被Rails自动调用。

我的代码如下所示:

class MyController < ApplicationController 
    def action1 
    # my code 
    respond_to do |format| 
     # Render with :json option automatically calls to_json and this calls as_json 
     format.js { render :json => @myobjects } 
    end 
    end 

    def action2 
    # a different code 
    respond_to do |format| 
     # This action should return a JSON object but using a different format 
     format.js { render :json => @myobjects } 
    end 
    end 

end 



class MyModel < ActiveRecord::Base 
    def as_json(options = {}) 
    # I would like to add a conditional statement here 
    # to write a different array depending on one param from the controller 
    { 
     :id => self.id, 
     :title => self.description, 
     :description => self.description || "", 
     :start => start_date1.rfc822, 
     :end => (start_date1 && start_date1.rfc822) || "", 
     :allDay => true, 
     :recurring => false 
    } 
    end 

end 

注意@myobjects对象是哪一类的集合是为MyModel。

任何帮助,将不胜感激。谢谢!

回答

2

在控制器中显式调用并传递参数。 as_json将返回字符串,并在字符串上调用as_json返回自身。这是相当普遍的做法。

respond_to do |format| 
    # Render with :json option automatically calls to_json and this calls as_json 
    format.js { render :json => @myobjects.as_json(params) } 
end 
+0

其实我也不知道为什么会这样的作品,但它确实... Rails的魔法...... 还是要谢谢你! –