Search code examples
ruby-on-railscontrollermany-to-manyone-to-many

How to get variables in controller, many to many and one to many in rails


I'm building a new project in rails (4.0) and I've got a question on how to get a variable in my controller. I have 2 models which have a many-2-to-many relationship, Leads and Properties. Next, my User model is linked via a one-to-many via a model Locations.

Users has one or many Locations, Location has one or many Properties. Lead has many Properties and Properties have many Leads.

Now in my User controller, I'm trying to have all leads that belong to a certain user.. Can someone please help me how to get this in my controller?

At this moment I have something like this, which is obviously incorrect.

def operator_leads
  if  current_user
    @user = User.find(current_user.id)
  else
    @user = nil
  end
  @leads = @user.property.each do |k|
    leads << k.leads
  end
end

UPDATE: my current models

class Location < ActiveRecord::Base
  has_many :properties, :dependent => :destroy
  belongs_to :user, :counter_cache => true
end

class Property < ActiveRecord::Base
  include Tokenable
  belongs_to :location
  has_one :user ,:through => :location
  has_many :leads, :through => :lead_properties
  has_many :lead_properties, :dependent => :delete_all
end

class User < ActiveRecord::Base  
   include Tokenable
  devise :database_authenticatable, :registerable, :confirmable,
         :recoverable, :rememberable, :trackable, :validatable
  has_many :locations, :dependent => :destroy 
  has_many :blogs
  has_many :admin_leads, :class_name => 'Lead', :foreign_key => 'admin_user_id'
  has_many :leads, :through => :properties
end

class Lead < ActiveRecord::Base
    has_many :properties, :through => :lead_properties
    has_many :lead_properties
    belongs_to :admin_user, :class_name => "User"
    has_many :users, :through => :properties
end

class LeadProperty < ActiveRecord::Base
    belongs_to :lead
    belongs_to :property 
    accepts_nested_attributes_for :lead
end

Solution

  • Use a nested has_many :through to define a User having many properties through Location:

    class User
      has_many :locations
      has_many :properties, through: :locations
      has_many :leads, through: :properties
    end
    
    class Location
      belongs_to :user
      has_many :properties
      has_many :leads, through: :property
    end
    
    class Property
      belongs_to :location
      has_many :leads
    end
    

    Then define your controller:

    def operator_leads
      @user = current_user  # You can use current_user in the view to avoid defining @user here.
      @leads = current_user.leads
    end
    

    Docs: http://guides.rubyonrails.org/association_basics.html#the-has-many-through-association