Rails高级协会
我想做这样的事情:
class MyModel < ActiveRecord::Base
has_many :locations
has_one :location, :class_name => 'Location', :join => "RIGHT JOIN locations ON locations.user_id=mymodels.user_id"
end
尽管 MyModel 有很多位置,但每个用户只能有一个位置。 我该如何定义呢?谢谢!
I would like to make smth like this:
class MyModel < ActiveRecord::Base
has_many :locations
has_one :location, :class_name => 'Location', :join => "RIGHT JOIN locations ON locations.user_id=mymodels.user_id"
end
So MyModel can only have one location for each user though it has many location.
How can I define that? Thx!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
模型名称的复数形式和单数形式的关联命名关联可能会令人困惑,还可能导致方法重叠。除了最佳实践之外,您通常不需要提供原始 SQL。你的情况也不例外。
看来MyModel也属于User。并且用户似乎与位置具有一对多关系,那么您可以执行以下操作:
假设基于发布的 SQL 的以下模型:
但是,如果用户有多个位置,您不知道将获得哪个位置地点。但如果至少有一个的话,你就一定会得到一个。
Naming associations such that you have an association for both the plural and singular forms of a model name can be confusing, it could also result in method overlap. Best practices aside, you usually don't need to supply raw SQL. Your case is no exception.
It looks like MyModel also belongs to User. And User appears to have a one to many relationship with Locations then you can do something like this:
Assumeing the following models based on the SQL posted:
However, you don't know which location you're going to get if the user has many locations. But you're guaranteed one if there is at least one.
我可能是错的......
您可以使用 MyModel.first.user.location 获取用户位置
I might be wrong ...
the you can get the user location with MyModel.first.user.location