【问题标题】:has_many association with non-traditional data modelhas_many 与非传统数据模型的关联
【发布时间】:2010-01-02 02:37:19
【问题描述】:

我正在与 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 模型的设置方式如下:

  • 身份证
  • user_id
  • friend_id
  • 朋友姓名

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

尝试做:

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

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

【问题讨论】:

    标签: ruby-on-rails associations has-many


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      这是我看到的问题所在:

      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

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

      【讨论】:

        猜你喜欢
        • 2012-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多