Rails has_many 3 个表之间的关联

发布于 2024-10-06 00:49:00 字数 696 浏览 10 评论 0原文

我有 3 个类:用户、自行车、交易。

一个用户可以拥有多辆自行车,而自行车只有一个用户(车主)。 交易有一辆自行车和一个用户(买家)...

在我的用户模型中,我有这些关联:

has_many :bicycles_owned, :class_name => "Bicycle", 
         :uniq => true, :foreign_key => "owner_id"

has_many :trans_bicycles_bought, :class_name => "Transaction",
         :foreign_key => "buyer_id"

has_many :bicycles_bought, :class_name=> "Bicycle", 
         :through => :trans_bicycles_bought,  :source => :bicycle

has_many :trans_bicycles_sold, :class_name => "Transaction", 
         :through => :bicycles_owned, :source => :transaction

现在我想要关联 bicycles_sold...我已经尝试了很多东西,但是我无法获得正确的代码..正确的参数...

I have 3 classes: User, Bicycle, Transaction.

A user can have many bicycles, and bicycle have only one user (owner).
The transaction have one bicycle, and one user (the buyer)...

In my user model I have these associations:

has_many :bicycles_owned, :class_name => "Bicycle", 
         :uniq => true, :foreign_key => "owner_id"

has_many :trans_bicycles_bought, :class_name => "Transaction",
         :foreign_key => "buyer_id"

has_many :bicycles_bought, :class_name=> "Bicycle", 
         :through => :trans_bicycles_bought,  :source => :bicycle

has_many :trans_bicycles_sold, :class_name => "Transaction", 
         :through => :bicycles_owned, :source => :transaction

Now I want the association bicycles_sold... I already tried a lot of things, but I can't get the right code.. the right arguments...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(2

赠我空喜 2024-10-13 00:49:00

怎么样:

has_many :bicycles_sold, :class_name => "Bicycle",
          :finder_sql => 'SELECT b.* FROM bicycles AS b ' +
                         'JOIN users AS u ON u.id = b.owner_id ' +
                         'JOIN transactions AS t ON t.bicycle_id = b.id ' +
                         'WHERE u.id = #{id}'

How about:

has_many :bicycles_sold, :class_name => "Bicycle",
          :finder_sql => 'SELECT b.* FROM bicycles AS b ' +
                         'JOIN users AS u ON u.id = b.owner_id ' +
                         'JOIN transactions AS t ON t.bicycle_id = b.id ' +
                         'WHERE u.id = #{id}'
猥︴琐丶欲为 2024-10-13 00:49:00

这里是您可能感兴趣的一篇文章。

我不确定 Rails 3 是否支持嵌套的 has_many :through,但 2.3.5 不支持。有一张(非常旧的)Rails 票。还有一个嵌套的 has_many :through 插件,它有一个 2.3.x 的实验分支。我不喜欢使用“实验性”的东西。

Here is an article you might be interested in.

I’m not sure if Rails 3 supports nested has_many :through, but 2.3.5 does not. There is a (very old) ticket for Rails. There is also a nested has_many :through plugin that is has an experimental branch for 2.3.x. I don’t like using things that are ‘experimental’.

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