如何设置此关联并拨打电话?

时间:2014-04-28 02:06:18

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

Ruby:2.0。

Rails:4.0.1

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

  • 用户

    • ID
  • 顺序

    • 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

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

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;博士

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

我需要设置user.commissions

的帮助

1 个答案:

答案 0 :(得分:2)

尝试一下:

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