【问题标题】:How to get variables in controller, many to many and one to many in rails如何在控制器中获取变量,在rails中多对多和一对多
【发布时间】:2016-05-23 22:19:20
【问题描述】:

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

用户有一个或多个位置,位置有一个或多个属性。 潜在客户有很多属性,属性有很多潜在客户。

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

此时我有这样的东西,这显然是不正确的。

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 one or many 是什么意思?

标签: ruby-on-rails controller many-to-many one-to-many


【解决方案1】:

使用嵌套的has_many :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

然后定义你的控制器:

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

【讨论】:

  • 该死,你打败了我!
  • 嗨,我不确定这是不是解决方案,因为我在潜在客户和属性之间存在多对多关系(通过表 Lead_properties)。我已经用我的模型更新了我的问题。我猜这会改变你的答案?
  • 不,没关系
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多