代码之家  ›  专栏  ›  技术社区  ›  xpepermint

Rails高级关联

  •  3
  • xpepermint  · 技术社区  · 14 年前

    我想让smth这样:

    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有许多位置,但每个用户只能有一个位置。 我该如何定义?谢谢!

    2 回复  |  直到 11 年前
        1
  •  4
  •   EmFi    11 年前

    命名关联,使您对模型名称的复数形式和单数形式都有关联,这可能会造成混淆,也可能导致方法重叠。撇开最佳实践不谈,您通常不需要提供原始SQL。你的情况也不例外。

    看起来mymodel也属于用户。用户似乎与地点有一对多的关系,然后您可以这样做:

    基于发布的SQL假设以下模型:

    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
  •  2
  •   wizztjh    14 年前

    我可能错了…

    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获取用户位置

    推荐文章