0

我正在与 has_many 关联作斗争。我有一个日记应用程序。示范选手如下:

  • 用户
  • 用户朋友
  • 用户食物档案

我希望能够获得用户朋友吃过的所有食物。所以,我希望能够得到: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
  • 用户身份
  • 朋友ID
  • 朋友名

我想user_food_profiles从朋友那里连接,以便我可以将用户朋友的当前user_food_profiles作为“条目”,但我尝试过的一切都没有奏效。我将如何设置此关联?

试图做:

  • 用户朋友:has_many :user_food_profiles, :as => 'entries'
  • 用户食物档案:belongs_to :friend, :foreign_key => 'friend_id'

关于如何使这项工作的任何想法?很想创建一个自定义 finder_sql 但我确信这可以与关联一起使用。

4

2 回答 2

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都很容易。

现在,如果关系是双向的,它会变得有点复杂,但我觉得这至少应该让你开始前进。

于 2010-01-14T10:36:34.170 回答
0

“朋友”不只是数据库中的另一个用户吗?

让您的 UserFriend 成为 many_to_many 关系(使用“has_and_belongs_to_many”或“has_many :through”):每个用户可以有多个用户作为朋友。然后,您可以毫无问题地将这些 user_id(如果您愿意,可以在名为“friend_id”的 many_to_many 表中)链接到他们的 foodprofile,因为它使用与 user.foodprofile 相同的链接。

于 2010-01-06T17:57:17.433 回答