Rails:通过关联 has_many - 我做对了吗?
我使用 Rails 3.1 构建照片共享 Web 应用程序。我只是想验证我的关联是否正确。
一些上下文:用户
有许多共享
。一个共享
有一个用户
(即“共享者”)、一张照片
和多个接收者< /代码>。
接收者
是任意用户
。
我使用直通关联的原因很简单,因为我想为共享照片的每个接收者存储附加数据。
class Photo < ActiveRecord::Base
has_many :shares
end
class Receiver < ActiveRecord::Base
belongs_to :share
belongs_to :user
end
class Share < ActiveRecord::Base
belongs_to :photo
belongs_to :user
has_many :receivers
has_many :users, :through => :receivers
end
class User < ActiveRecord::Base
has_many :receivers
has_many :shares, :through => :receivers
end
然后可以使用 shares
类方法检索User
共享照片吗?
User.first.shares
# => [<#Share:0x000>, ...]
然后可以使用 receivers
类方法来检索 User
收到的共享吗?
User.first.receivers
# => [<#Receiver:0x000>, ...]
我做对了吗?
I building a photo sharing web application using Rails 3.1. I just want to verify that I got the associations right.
Some context: A User
has many Share
. A Share
has one User
(i.e the "sharer"), one Photo
and many Receiver
. A Receiver
is a arbitrary User
.
The reason why I'm using a through association is simply because I want to store additional data for each receiver of the shared photo.
class Photo < ActiveRecord::Base
has_many :shares
end
class Receiver < ActiveRecord::Base
belongs_to :share
belongs_to :user
end
class Share < ActiveRecord::Base
belongs_to :photo
belongs_to :user
has_many :receivers
has_many :users, :through => :receivers
end
class User < ActiveRecord::Base
has_many :receivers
has_many :shares, :through => :receivers
end
Retreiving a User
shared photos could then be performed using the shares
class method?
User.first.shares
# => [<#Share:0x000>, ...]
Retreiving a User
received shares could then be performed using the receivers
class method?
User.first.receivers
# => [<#Receiver:0x000>, ...]
Did I get this right?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我不久前做了类似的事情,我没有测试这段代码,所以尝试一下它,看看它是否真的是你所需要的,它可能会为你指明正确的方向。
如果你的工作我不认为改变它的意义,这段代码有点复杂,但你没有接收器模型,一切都通过共享模型。
I did something similar a while ago, I didn't test this code, so play around with it and see if it actually is what you need, it may point you in the right direction though.
If yours work I don't see the point of changing it, this code is a bit more complex but you dont have a Receiver model, everything goes through the Share model.