2016-01-05 30 views
0

傢伙,我嘗試使用DB關係一個兩個表之間化JSON得到rails4數據到一個Rails4使用json.array重命名

Json的元素名稱這是我的Json代碼

json.array!(@users) do |user| 
    json.extract! user, :id 
    json.extract! user, :name 
    json.extract! user, :email 
    json.extract! user, :city 

    # now trying to get the user nickname from the another table 
    json.extract! user.nickname , name 

end 

代碼json.extract! user.nickname , name真心回報用戶暱稱,但因爲該領域稱爲name其替換它的JSON數組,而不是用戶的真實姓名

所以我怎麼能在這種情況下,重命名的鍵名嗎?停止覆蓋元素!

回答

0

我在控制器

format.json { render json: @users.as_json(only: [:id, :name, :email,:city, :created_at, :updated_at], include: [:second_model_name , :third_model_name]) } 

解決它通過加入這一行和在文件中index.json.jbuilder視圖users夾我剛添加

json.array!(@users) do |user| 
    json.extract! user, :id, :name, :email ,:city ,:created_at , :second_model_name, :third_model_name 
end