Ruby:2.0。
Rails:4.0.1
我有2个模型:User
和Orders
这是他们的相关信息:
用户
顺序
我(当前)模型的相关部分:
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.commissions
答案 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