2010-01-02 66 views
0

我正在努力與has_many關聯。我有一個日記應用程序。該模型的球員如下:has_many與非傳統數據模型的關聯

  • 用戶
  • UserFriend
  • UserFoodProfile

我希望能夠得到在該用戶的朋友都吃光了所有的食物。所以,我想能夠得到:current_user.friends.profiles

我已經設置好關聯到目前爲止,以便我能夠訪問current_user.friends,但現在我希望能夠獲得所有朋友的條目以及最近30天。

這裏是我的模型

class User < ActiveRecord::Base 

    cattr_reader :per_page 
    @@per_page = 20 

    has_many :user_food_profiles 
    has_many :preferred_profiles 
    has_many :food_profiles, :through => :user_food_profiles 
    has_many :weight_entries 
    has_one :notification 
    has_many :user_friends 
    has_many :friendships, :class_name => "UserFriend", :foreign_key => "friend_id" 
    has_many :friends, :through => :user_friends 

class UserFriend < ActiveRecord::Base 

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

class UserFoodProfile < ActiveRecord::Base 
    belongs_to :user 
    belongs_to :food_profile 
    belongs_to :post 

的UserFriend模型建立方式如下:

  • ID
  • USER_ID
  • friend_id
  • FRIEND_NAME

我想連接到朋友的user_food_profiles,以便我可以將用戶朋友的當前user_food_profiles作爲「條目」,但我嘗試過的所有內容都無法使用。我將如何設置此關聯?

試圖這樣做:

  • UserFriend:has_many :user_food_profiles, :as => 'entries'
  • UserFoodProfile:belongs_to :friend, :foreign_key => 'friend_id'

如何使這項工作任何想法?試圖創建一個自定義finder_sql,但我相信這可以與關聯一起工作。

回答

0

是不是「數據庫中的另一個用戶」的「朋友」?

讓你的用戶朋友成爲一個many_to_many關係(或者用「has_and_belongs_to_many」或者「has_many:through」):每個用戶可以有幾個用戶成爲朋友。 然後,您可以將這些user_ids(如果您喜歡,可以在many_to_many表中稱爲「friend_id」)鏈接到其食譜,因爲它使用的鏈接與user.foodprofile相同。

0

這是我看到的是這個問題行:

class User < ActiveRecord::Base 
    # <snip/> 
    has_many :friendships, 
       :class_name => "UserFriend", 
       :foreign_key => "friend_id" 

我假設你使用一個連接表在這裏被稱爲user_friend。這意味着那裏的外鍵應該是「user_id」。現在

,除非你要存儲額外的元數據在UserFriend模型,它不是必需的 - 你可以像這樣一個自我指涉的has_and_belongs_to_many關係脫身:

has_and_belongs_to_many :friends, 
          :class_name => "User", 
          :join_table => "user_friends", 
          :foreign_key => "user_id", 
          :association_foreign_key => "friend_id" 

這樣做,你必須要做的是很容易的就是user.friends.profiles

現在,如果這種關係是雙向的,它會變得更復雜一點,但我覺得這應該至少讓你開始一路走來。