开发者

Rails advanced association

I would like to make smth like this:

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

So MyModel can only have one location for each user though it has many location. How can I de开发者_如何学编程fine that? Thx!


Naming associations such that you have an association for both the plural and singular forms of a model name can be confusing, it could also result in method overlap. Best practices aside, you usually don't need to supply raw SQL. Your case is no exception.

It looks like MyModel also belongs to User. And User appears to have a one to many relationship with Locations then you can do something like this:

Assumeing the following models based on the SQL posted:

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

However, you don't know which location you're going to get if the user has many locations. But you're guaranteed one if there is at least one.


I might be wrong ...

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

the you can get the user location with MyModel.first.user.location

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜