0
User
 #

Cars
 belongs_to :father, :class_name => "User"
 belongs_to :user

user = User.find(1)

伙计们帮助我可以通过键入user.cars(使用搜索汽车user_id)来获取用户的汽车,但是我究竟怎样才能让它使用father_id进行搜索?

显然我可以做一个Car.find_by_creator_id(...),但我想知道是否有一个轨道解决方案。

谢谢

4

1 回答 1

1

您可以设置关系的另一侧并在模型:inverse_of中为每个关系指定。User就像是

class User < ActiveRecord::Base
  has_many :father_cars, :class_name => "Car", :inverse_of => :father
  has_many :cars, :inverse_of => :user

  # ...
end

Cars < ActiveRecord::Base
  belongs_to :father, :class_name => "User", :inverse_of => :father_cars
  belongs_to :user, :inverse_of => :cars

  # ...
end

然后,您可以访问:father

u = User.find(1)
cars = user.father_cars
于 2012-07-09T14:19:10.800 回答