Extended Rails Association

I would like to do smth as follows:

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, although it has many locations. How can I determine this? thank!

+3
source share
2 answers

The naming of associations, so that you have an association of both multiple and singular forms of the model name, can be confusing, it can also override the method. Best practice aside, you usually don't need to supply raw SQL. Your case is no exception.

, 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

, , . , .

+4

, ...

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

+2

Source: https://habr.com/ru/post/1775966/


All Articles