我在rails(4.0)中构建了一个新项目,我对如何在控制器中获取变量提出了疑问。我有2个模型,它们具有多对多关系,即引线和属性。接下来,我的用户模型通过模型位置通过一对多链接。
用户有一个或多个位置,位置有一个或多个属性。 Lead有很多属性,属性有很多潜在客户。
现在,在我的用户控制器中,我尝试拥有属于某个用户的所有潜在客户。有人可以帮助我如何在我的控制器中获取此功能吗?
此刻我有这样的事情,这显然是不正确的。
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
答案 0 :(得分:1)
使用嵌套的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