2013-03-20 147 views
0

我想对JSON覆盖默认模型值,而是重写它创建重复的哈希Rails的模型as_json覆盖默认值

我的模型:

class HomeScreenButton < ActiveRecord::Base 
    belongs_to :product_category  
    validates :product_category_id, :x, :y, :presence => true 
    attr_accessible :product_category_id, :x, :y 

    def as_json(options={}) 
    hash = super(options) 
    hash.merge({ 
     :product_category_id => "fdfd" 
    }) 
    end 
end 

我的控制器:

def index 
    @home_screen_buttons = HomeScreenButton.all 

    respond_to do |format| 
     format.html # index.html.erb 
     format.json { render json: @home_screen_buttons} 
    end 
end 

当我打开json时,它显示我为product_category_id的副本:[{"created_at":"2013-03-17T11:14:32Z","id":1,"product_category_id":5,"updated_at":"2013-03-17T11:14:32Z","x":300,"y":200,"product_category_id":"dfdffff"}]

回答

1

有没有需要合并哈希

def as_json(options={}) 
    hash = super(options) 
    hash[:product_category_id] = "fdfd" 
    hash 
end 
+0

,也仍然感到重复。使用“product_category_id”而不是:product_category_id在两个示例中解决了我的问题。 – 2013-03-21 10:34:27