【发布时间】: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 => 'entries' - 用户食物档案:
belongs_to :friend, :foreign_key => 'friend_id'
关于如何完成这项工作的任何想法?很想创建一个自定义的 finder_sql,但我确信这可以与关联一起使用。
【问题讨论】:
标签: ruby-on-rails associations has-many