我正在与 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 但我确信这可以与关联一起使用。