ruby-on-rails – 从JSON访问虚拟属性
发布时间:2020-12-17 01:54:45 所属栏目:百科 来源:网络整理
导读:我的设置:Rails 2.3.10,Ruby 1.8.7 我尝试从JSON调用中访问模型中的虚拟属性,但没有成功.假设我有以下型号和控制器代码 class Product name,description,price,attr_accessor :discounted_price endclass Price discountendclass ProductsController def sh
我的设置:Rails 2.3.10,Ruby 1.8.7
我尝试从JSON调用中访问模型中的虚拟属性,但没有成功.假设我有以下型号和控制器代码 class Product name,description,price,attr_accessor :discounted_price end class Price discount end class ProductsController def show @product = Product.find(params[:id]) respond_to do |format| format.html # show.html.erb format.json { render :json => @product } end end end 我喜欢的是让JSON输出还包括Product.discounted_price,它是为每次调用实时计算的,即discounted_price = Price.discount * Product.price.有没有办法实现这个目标? 解: def discounted_price ...# do the calculation here end 在JSON调用中执行此操作 store = Store.find(1) store.as_json(:include => :products,:methods => :discounted_price) 解决方法
您可以使用:methods参数运行to_json以包含这些方法的结果.
render :json => @product.to_json(:methods => :discounted_price) (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |