2016-05-22 8 views
0

私はレール(4.0)で新しいプロジェクトを構築していますが、コントローラで変数を取得する方法について質問があります。私は多くの2対多の関係、リードとプロパティを持つ2つのモデルを持っています。次に、私のUserモデルは、モデルLocationsを介して一対多を介してリンクされています。コントローラ内の変数の取得方法、多対多、一対多数のレール

ユーザーには1つ以上の場所があり、場所には1つまたは複数のプロパティがあります。 鉛には多くのプロパティがあり、プロパティには多くのリードがあります。

ユーザーコントローラーで、特定のユーザーに属するすべてのリードを取得しようとしています。コントローラーでこれを取得する方法を教えてもらえますか?

この時点で私は明らかに間違っているようなものがあります。

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:私の現在のモデル

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つ以上ある」とはどういう意味ですか? – fbelanger

答えて

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

+0

ねえ、あなたは私にそれを打つ! – fbelanger

+0

こんにちは、私はリードとプロパティ(テーブルのlead_propertiesを介して)の間に多対多の関係を持っているので、これが解決策であるかどうかはわかりません。私は私のモデルで私の質問を更新しました。私はこれがあなたの答えを変えると思っていますか? –

+0

いいえ、それは問題ではありません –

関連する問題