在里面制作几种方法包括

时间:2013-10-17 17:43:29

标签: ruby-on-rails ruby json

我试图在rails中添加一些包含as_json的方法,但第二种方法包括在json上显示方法。这是代码

            format.json { render :json => { :projects => @projects.as_json(:include => [
            :retail, 
            :property => {:methods => :name}, 
            :user => {:methods => [:name, :address] } ] ) } }

这是生成的json:

{"projects":[{"comment":null,"contractor":1,"created_at":"2013-10-17T16:57:36Z","id":5,"property_id":3,"retail_id":1,"updated_at":"2013-10-17T16:57:36Z","user_id":2,"retail":{"address":null,"created_at":"2013-10-16T22:29:38Z","id":1,"name":"asdasdsa","phone":"6677969224","property_id":null,"social_reason_id":null,"updated_at":"2013-10-17T17:18:09Z","web":"www.boxie.io"},"property":{"city":"Culiacan","colony":"Fracc Los Sauces","coordinates":"(24.7802016, -107.34894730000002)","country_id":1,"created_at":"2013-10-17T00:56:32Z","external_number":null,"id":3,"internal_number":2848,"population":null,"state_id":4,"street":"Alame\u00f1a","updated_at":"2013-10-17T00:56:32Z","zipcode":8028,"name":"Calle Alame\u00f1a,  Fracc Los Sauces, 8028, Culiacan, Campeche Mexico"}}]}

正如您所看到的那样,用户信息没有出现在json上。

谢谢

1 个答案:

答案 0 :(得分:0)

你没有正确地包装它们,你的第二和第三个儿童协会应该是哈希。

@projects.as_json(:include => [
  :retail, 
  { :property => {:methods => :name } }, 
  { :user => {:methods => [:name, :address] } } 
]