将朋友加入其他模型
我在 ActiveRecord 中构建复杂的连接时仍然遇到问题。
我有一个使用 Steve Ehrenberg (http://dnite.org) 的 HasManyFriends 插件的用户模型。
然后我有一个 UserFeedEvent 模型,它将用户链接到 FeedEvent 模型。
我想要实现的是找到链接到用户朋友的所有FeedEvents。
我应该如何编写 ActiveRecord 查询?
这是我的模型:
class User < ActiveRecord::Base
has_many_friends
has_many :feed_events, :through => :user_feed_events, :dependent => :destroy
has_many :user_feed_events, :dependent => :destroy
end
class UserFeedEvent < ActiveRecord::Base
belongs_to :feed_event, :dependent => :destroy
belongs_to :user
end
class FeedEvent < ActiveRecord::Base
has_many :user_feed_events, :dependent => :destroy
has_many :users, :through => :user_feed_events
serialize :data
end
提前致谢! 奥古斯托
I'm still having trouble building complex joins in ActiveRecord.
I have a User model that is using the HasManyFriends plugin by Steve Ehrenberg (http://dnite.org).
Then I have a UserFeedEvent model that links users to a FeedEvent model.
What I'd like to achieve is to find all the FeedEvents linked to the friends of a User.
How should I write my ActiveRecord query?
Here are my models:
class User < ActiveRecord::Base
has_many_friends
has_many :feed_events, :through => :user_feed_events, :dependent => :destroy
has_many :user_feed_events, :dependent => :destroy
end
class UserFeedEvent < ActiveRecord::Base
belongs_to :feed_event, :dependent => :destroy
belongs_to :user
end
class FeedEvent < ActiveRecord::Base
has_many :user_feed_events, :dependent => :destroy
has_many :users, :through => :user_feed_events
serialize :data
end
Thanks in advance!
Augusto
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
深入挖掘HasManyFriends源代码使我相信以下内容应该有效(或完成一半):
编辑:发现
源代码
不能指向另一个:has_many :through
关联。所以你可以尝试更新的版本。不幸的是,
HMF
插件有两个单向友情链接,这意味着完整列表需要 2 个数据库查询。Digging through HasManyFriends source leads me to believe that the following should work (or be half-way through):
EDIT: found out that
source
cannot point to another:has_many :through
association. So you could try the updated version.Unfortunately the
HMF
plugin has two one-way friendship links, which means full list requires 2 DB queries.我找到了一个有效且更传统的 SQL 解决方案:
如果您有更有效/更优雅的方法来执行相同的操作,请告诉我!
I found a working and more traditional SQL solution:
If you have a more efficient / more elegant way of doing the same, please let me know!