http://stackoverflow.com/questions/3462754/rails-object-relationships-and-json-rendering
主表:
- class Pipeline < ActiveRecord::Base
- has_many :sensors , :foreign_key => :pipeline_code ,:primary_key => :code
- end
子表:
- class Sensor < ActiveRecord::Base
- belongs_to :pipeline, :foreign_key => :pipeline_code ,:primary_key => :code
- end
在conroler里面写
- # 获取一个特定的桩孔和其属于的传感器信息
- def sensorsInThePipelineByCode()
- @pipeline = Pipeline.where(["code = ? ",params[:code]]).first;
- if respond_to do |format|
- format.html { render action: "show" }
- format.json {
- render json: @pipeline.to_json(:include => :sensors)
- }
- end
- end
- end
主要是:
- @pipeline.to_json(:include => :sensors)
如果是多级关联 可以这么写 :
- @pipeline_json.to_json(:include => {:sensors => {:include => :sensor_type }})