2010-11-20 60 views
3

我想使水木清华这样的:Rails的先进协会

class MyModel < ActiveRecord::Base 
    has_many :locations 
    has_one :location, :class_name => 'Location', :join => "RIGHT JOIN locations ON locations.user_id=mymodels.user_id" 
end 

所以为MyModel只能为每个用户一个位置,尽管它有很多的位置。 我该如何定义?谢谢!

回答

4

命名协会如您有关联的两个复数,模型名称的单数形式可能会造成混淆,也可能导致方法重叠。除了最佳做法外,您通常不需要提供原始SQL。你的情况也不例外。

它看起来像MyModel也属于用户。和用户似乎有一个与位置的许多关系,那么你可以做这样的事情:

基于SQL Assumeing以下型号发布时间:

class User < ActiveRecord::Base 
    has_many :my_models 
    has_many :locations 
end 

class Location <ActiveRecord::Base 
    belongs_to :my_model 
    belongs_to :user 
end 



class MyModel < ActiveRecord::Base 
    has_many :locations 
    belongs_to :user 
    has_one :user_location, through => :user, :source => :location 
end 

但是,你不知道哪个位置如果用户有很多位置,你会得到。但是如果至少有一个,你就保证有一个。

2

我可能是错的...

class MyModel < ActiveRecord::Base 
    has_many :location 
    belongs_to :user 
end 

class Location< ActiveRecord::Base 
    belong_to :my_model 
end 

class User< ActiveRecord::Base 
    has_one :my_model 
end 

的你可以用MyModel.first.user.location获取用户位置

+1

你有has_many关联,所以你应该能够将它定义为某种连接。另外想象一下100个结果的列表,并且您只希望对数据库有1个请求。 – xpepermint 2010-11-20 13:17:58