Reputation: 36273
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 define that? Thx!
Upvotes: 3
Views: 358
Reputation: 23450
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.
Upvotes: 4
Reputation: 7041
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
Upvotes: 2