【问题标题】:How can I set up this association and make calls?如何建立此关联并拨打电话?
【发布时间】:2014-04-28 02:06:17
【问题描述】:

Ruby:2.0。

导轨:4.0.1

我有 2 个模型:UserOrders 这是他们的相关信息:

  • 用户

    • 身份证
  • 订购

    • user_id
    • distributor_id

以及我(当前)模型的相关部分:

class User < ActiveRecord::Base
  has_many :orders
end

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :distributor, class_name: User
end

基本上,用户的订单是他们下的订单,但每个用户也有“佣金” - 并且需要能够引用他们设置为分销商的所有订单。所以:

user = User.find 7
user.orders // would return all orders where user_id = 7 (this works)
user.commissions // would return all Orders where distributor_id = 7 (this is what I need help with)

如何在用户模型中进行设置?


我想我之前可能不清楚,这里有一个 tl;dr

  • user.orders 查找 user_id = user.id 的订单
  • user.commissions 查找distributor_id = user.id 的订单

我需要帮助设置user.commissions

【问题讨论】:

  • 尝试给一个这样的foreign_key选项belongs_to :distributor, class_name: User, foreign_key: distributor_id

标签: ruby-on-rails ruby-on-rails-4


【解决方案1】:

试试这个:

class User < ActiveRecord::Base
  has_many :orders
  has_many :commissions, class_name: Order, foreign_key: :distributor_id
end

class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :distributor, class_name: User
end

现在打电话

User.find(7).commissions

【讨论】:

  • 这似乎不起作用 - 我遇到了这个:2.0.0p247:001 > User.first.commissions User Load (0.4ms) SELECT "users".* FROM "users" ORDER BY "users"."id" ASC LIMIT 1 NameError: uninitialized constant User::Distribution
  • 我们越来越近了,但是您的更新会运行此查询(来自 rails 控制台):Order Load (2.2ms) SELECT "orders".* FROM "orders" WHERE "orders"."user_id" = ? [["user_id", 22]] --- 我需要它来执行 where "orders"."distributor_id" = ?
  • 知道了。好的 - 尝试添加外键,因为我刚刚更新了我的答案,这应该可以满足您的需求!
  • 成功了 - 感谢您在这个过程中一直支持我! (也感谢您成为 3 个答案中唯一一个真正准备好我的问题的人。)
猜你喜欢
  • 1970-01-01
  • 2014-12-20
  • 1970-01-01
  • 2017-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-08-26
相关资源
最近更新 更多