如何获取控制器中的变量,rails中的多对多和一对多

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

我正在 rails (4.0) 中构建一个新项目,我有一个关于如何在我的控制器中获取变量的问题。我有 2 个具有多对多关系的模型,Leads 和 Properties。接下来,我的用户模型通过模型位置通过一对多链接。

用户有一个或多个位置,位置有一个或多个属性。 Lead 有很多 Properties,而 Properties 有很多 Leads。

现在在我的用户控制器中,我正在尝试拥有属于某个用户的所有潜在客户。有人可以帮助我如何在我的控制器中获取它吗?

此刻我有这样的事情,显然是不正确的。

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

更新:我当前的模型

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

使用嵌套 has_many :through 通过位置定义具有多个属性的用户:

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

然后定义你的控制器:

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

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