看板 Ruby 關於我們 聯絡資訊
※ 引述《godfat (godfat 真常)》之銘言: : : 推 kewang:這樣子寫我知道可以,可是我想讓user可以顯示全部的欄位, 09/08 15 : : → kewang:因為我要to_json,照文中的寫法會無法顯示laptop.*,只會出 09/08 16 : : → kewang:現user.name, user.laptop_id而已 09/08 16 : 提供一個笨方法 : u = User.first : u.attributes.merge('laptop' => u.laptop.attributes).to_json : or : l = Laptop.first : l.attributes.merge('users' => l.users.map(&:attributes)).to_json : 重點在於,反正 attributes 會給你所有的資料,就自己組合吧 class User belongs_to :laptop delegate :color, :to => :laptop, :prefix => :laptop end @user.laptop_color # => @user.laptop.color @user.to_json(:methods => :laptop_color) -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 58.114.185.227
kewang:感謝,但這個好像要把所有的attributes都列上去,比較不方 09/09 15:12
kewang:便,但還是很感謝 09/09 15:13