Rails高级协会

发布于 2024-10-03 11:19:45 字数 281 浏览 0 评论 0原文

我想做这样的事情:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

浅忆 2024-10-10 11:19:45

模型名称的复数形式和单数形式的关联命名关联可能会令人困惑,还可能导致方法重叠。除了最佳实践之外,您通常不需要提供原始 SQL。你的情况也不例外。

看来MyModel也属于User。并且用户似乎与位置具有一对多关系,那么您可以执行以下操作:

假设基于发布的 SQL 的以下模型:

class User < ActiveRecord::Base
  has_many :my_models
  has_many :locations
end

class Location <ActiveRecord::Base
  belongs_to :my_model
  belongs_to :user
end



class MyModel < ActiveRecord::Base
  has_many :locations
  belongs_to :user
  has_one :user_location,  through => :user, :source => :location
end

但是,如果用户有多个位置,您不知道将获得哪个位置地点。但如果至少有一个的话,你就一定会得到一个。

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:

class User < ActiveRecord::Base
  has_many :my_models
  has_many :locations
end

class Location <ActiveRecord::Base
  belongs_to :my_model
  belongs_to :user
end



class MyModel < ActiveRecord::Base
  has_many :locations
  belongs_to :user
  has_one :user_location,  through => :user, :source => :location
end

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.

若能看破又如何 2024-10-10 11:19:45

我可能是错的......

class MyModel < ActiveRecord::Base
  has_many :location
  belongs_to :user
end

class Location< ActiveRecord::Base
  belong_to :my_model
end

class User< ActiveRecord::Base
  has_one :my_model
end

您可以使用 MyModel.first.user.location 获取用户位置

I might be wrong ...

class MyModel < ActiveRecord::Base
  has_many :location
  belongs_to :user
end

class Location< ActiveRecord::Base
  belong_to :my_model
end

class User< ActiveRecord::Base
  has_one :my_model
end

the you can get the user location with MyModel.first.user.location

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文