查找has_many:通过

查找has_many:通过

问题描述:

我有3个模型:用户,客户,问题。下面是这些模型查找has_many:通过

代码

客户模式:

class Customer < ActiveRecord::Base 
    belongs_to :se 
    belongs_to :user 
    has_many :issues 
end 

问题型号:

class Issue < ActiveRecord::Base 
    belongs_to :customer 
end 

用户模式:

class User < ActiveRecord::Base 
    has_many :ses 
    has_many :customers 
    has_many :issues, :through => :customers 

    devise :database_authenticatable, :registerable, 
     :recoverable, :rememberable, :trackable, :validatable 

    attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name,  :last_name, :cell_ph, :area 


end 

我想只显示事项,属于特定用户。我在做这项工作时遇到问题。有人可以建议我可以创建一个索引方法来完成这个任务吗?

这里是我的索引方法,其中我试图用色器件的CURRENT_USER方法来识别谁在给视图登录的用户:

def index 
    @issues = Issue.where(:user == :current_user) 

    respond_to do |format| 
     format.html # index.html.erb 
     format.xml { render :xml => @issues } 
    end 
    end 

你不能做你正在做什么,因为一个问题没有用户。

根据Rails指南(http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association会话的第二个示例),您可以使用has_many :through嵌套has_many

所以,你应该能够做到这一点:

current_user.issues

+0

谢谢!这是帮助我解决问题的好方向。 – 2012-02-03 06:44:22

除了罗德里戈的回答,您可以在这条线的一些语法错误:

@issues = Issue.where(:user == :current_user) 

这是永远不会返回任何因为:user == :current_user正在执行两个不同的Ruby对象的比较。这总是返回错误,所以你的陈述基本上等于Issue.where(false)

这是更接近你需要的东西:

@issues = Issue.where(:user => current_user) 

这仍然不能解决你的问题(Issue没有多少User S),但至少含义是正确的。

+0

感谢您的澄清。这对我的学习很有帮助。 – 2012-02-03 06:45:52