Rails模型as_json覆盖默认值

时间:2013-03-20 20:38:12

标签: ruby-on-rails ruby-on-rails-3

我尝试覆盖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 个答案:

答案 0 :(得分:1)

无需合并哈希

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