Ruby on rails 与非传统数据模型有很多联系
我正在与一个有很多联系的人斗争。我有一份日记申请表。模型参与者如下所示:Ruby on rails 与非传统数据模型有很多联系,ruby-on-rails,associations,has-many,Ruby On Rails,Associations,Has Many,我正在与一个有很多联系的人斗争。我有一份日记申请表。模型参与者如下所示: 使用者 用户朋友 UserFoodProfile 我希望能够获得用户朋友吃过的所有食物。因此,我希望能够获得:当前用户.friends.profiles 到目前为止,我已经正确地设置了关联,以便能够访问当前的\u user.friends,但现在我希望能够获得过去30天内所有朋友的条目 这是我的模型 class User < ActiveRecord::Base cattr_reader :per_page
- 使用者
- 用户朋友
- UserFoodProfile
当前用户.friends.profiles
到目前为止,我已经正确地设置了关联,以便能够访问当前的\u 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
class用户:用户\u食物\u档案
有很多:权重项
有一个:通知
有很多:用户朋友
有很多:友谊,:class\u name=>“UserFriend”,:foreign\u key=>“friend\u id”
有很多:朋友,:通过=>:用户\u朋友
类UserFriend“User”,:foreign\u key=>“friend\u id”
类UserFoodProfile
UserFriend模型的设置方式如下:
- 身份证
- 用户id
- 朋友身份证
- 朋友的名字
user\u food\u profiles
,这样我就可以以“条目”的形式获取用户朋友当前的user\u food\u profiles
,但我尝试的一切都不起作用。我将如何设置此关联
尝试做:
- UserFriend:
有很多:用户食物档案,:as=>“条目”
- UserFoodProfile:
属于\u to:friend,:foreign\u key=>“friend\u id”
然后,您可以将这些用户id(如果愿意,可以在名为“friend\u id”的多对多表中)链接到他们的foodprofile,而不会出现问题,因为它使用的链接与user.foodprofile相同。我认为这是问题所在:
class User < ActiveRecord::Base
# <snip/>
has_many :friendships,
:class_name => "UserFriend",
:foreign_key => "friend_id"
要做到这一点,您所要做的就是非常轻松地user.friends.profiles
现在,如果关系是双向的,它会变得更复杂一些,但我觉得这至少应该让你一路开始
has_and_belongs_to_many :friends,
:class_name => "User",
:join_table => "user_friends",
:foreign_key => "user_id",
:association_foreign_key => "friend_id"