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"}]
,也仍然感到重複。使用「product_category_id」而不是:product_category_id在兩個示例中解決了我的問題。 – 2013-03-21 10:34:27