2015-12-29 84 views
0

我有一個朋友表,合併兩個Rails模型

create_table "friendships", force: :cascade do |t| 
    t.integer "user_id" 
    t.integer "friend_id" 
    t.datetime "created_at", null: false 
    t.datetime "updated_at", null: false 
    t.string "name" 
end 

當用戶添加好友的友誼模式創造了一個新的記錄有唯一ID的user_id一個friend_idname值。

在我的角度應用程序,我有一個模板,重複每個friendship in friendships

這是JSON結果當朋友已經加入,

[{"id":17,"friend_id":3,"name":"Kees Keesen"}] 

的id是友誼的id和friend_id是朋友的實際用戶ID。

所以我現在正在做的是複製我的數據。我有一個名稱,電子郵件等用戶模型。但是,當我添加一個朋友,我必須添加一個名稱值(和更多)的友誼記錄。

這是users.json JSON結果,

{"id":3,"email":"[email protected]","name":"Kees Keesen"} 

所以是有可能保持友誼unqique ID(我需要刪除的友誼紀錄),但做一個鏈接,用戶模型所以我不必複製我的數據?

*更新*

這裏是我的友誼控制器,

def index 
    friends = current_user.friendships.as_json 
    # friends = current_user.friends.as_json(:only => [:name, :email, :id]) 
    render :json => friends 
end 

我已經添加到了我的用戶模型,

has_many :friendships 
has_many :friends, :through => :friendships 
has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
has_many :inverse_friends, :through => :inverse_friendships, :source => :user 

這給我的友誼模式,

belongs_to :user 
belongs_to :friend, :class_name => "User" 

我已經移除的友誼表的名稱列中,JSON輸出,友誼是現在,

[{"id":2,"user_id":1,"friend_id":1,"created_at":"2015-12-29T19:24:28.788Z","updated_at":"2015-12-29T19:24:28.788Z"}] 

回答

0

在事物的角度側,你應該做的方法通過ID,它訪問獲取用戶幕後的緩存。然後,當你獲得友誼時,用這種方法替換它們所代表的用戶對象的id。如果用戶已經被看到,那麼你不需要再從服務器請求它。 JSON格式具有不能表示鏈接的缺點,所以我們傾向於使用ID來代替,並且只要我們獲取對象就將它們變成鏈接。

1

這裏幸福的方式是與自我指涉聯想。

class User < ActiveRecord::Base  
    has_many :friendships 
    has_many :friends, :through => :friendships 
    has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id" 
    has_many :inverse_friends, :through => :inverse_friendships, :source => :user 
end 

class Friendship < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :friend, class_name: "User" 
end 

有了這個解決方案,你會得到的數據結構約束的唯一ID,您的用戶user_id,併爲友誼的倒數方面的friend_id,這兩者指向User模型,以避免複製。這是一種很常見的做事方式。

這裏有一個註釋:inverse_friendships用於查詢某個用戶是由誰添加的,而不是他們自己添加的用戶。

UPDATE

爲了通過Friendship訪問User信息,它可以委派屬性要求:

class Friendship < ActiveRecord::Base 
    ... snip ... 

    delegate :name, :email, to: :friend 
end 

希望這有助於!

+0

感謝您的意見。我可能會錯誤地應用代碼,但似乎沒有改變。你會期望json是什麼?另外,如果我在'友情「模型中註釋掉代碼,json仍然會呈現相同的效果,換句話說友情模型似乎沒有做任何事情。我看到你從Railscast獲得了代碼。這也是我的嚮導。 –

+0

如果你的JSON根本沒有改變,你應該重新啓動一切。這是非常不同的代碼;)最簡單的事情是檢查並確保您的JSON表示沒有名稱字段。 –

+0

嗯。我關閉了我的Rails服務器。從友誼表中刪除了名稱列,重新設置了我的數據庫並重新調入,但仍然沒有更改json輸出。我已更新我的問題以反映更改。也許你可以發現我做錯了什麼?也許在控制器中。 –