rails 中把关联的数据表单 直接变成 json对象 渲染

178 篇文章 0 订阅


http://stackoverflow.com/questions/3462754/rails-object-relationships-and-json-rendering

主表:

  1. class Pipeline < ActiveRecord::Base  
  2.     has_many  :sensors ,    :foreign_key => :pipeline_code ,:primary_key => :code  
  3. end  

子表:
  1. class Sensor < ActiveRecord::Base  
  2.     belongs_to :pipeline:foreign_key => :pipeline_code ,:primary_key => :code  
  3. end  


在conroler里面写 

  1. # 获取一个特定的桩孔和其属于的传感器信息  
  2.    def sensorsInThePipelineByCode()  
  3.        @pipeline = Pipeline.where(["code = ? ",params[:code]]).first;  
  4.        if respond_to do |format|  
  5.            format.html { render action: "show" }  
  6.            format.json {  
  7.                render json: @pipeline.to_json(:include => :sensors)  
  8.            }  
  9.          end  
  10.        end  
  11.    end  

主要是:
  1. @pipeline.to_json(:include => :sensors)  

如果是多级关联 可以这么写 :

  1. @pipeline_json.to_json(:include => {:sensors => {:include => :sensor_type }})  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值