在has_many上找到:通过

时间:2012-02-03 02:23:03

标签: ruby-on-rails-3 devise

我有3个模型:用户,客户,问题。以下是这些模型的代码

客户模式:

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

我想只显示属于特定用户的问题。我在做这项工作时遇到了问题。有人可以建议我如何创建一个可以实现此目的的索引方法吗?

这是我的索引方法,我正在尝试使用devise的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

2 个答案:

答案 0 :(得分:1)

由于问题没有用户,你无法做你正在做的事情。

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

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

current_user.issues

答案 1 :(得分:1)

除罗德里戈的答案外,你还有一些不好的语法:

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

由于:user == :current_user正在执行两个不同的Ruby Symbol对象的比较,因此永远不会返回任何结果。这总是返回false,因此您的语句基本上等于Issue.where(false)

这更接近您的需求:

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

这仍然无法解决您遇到的问题(Issue没有多少User s),但至少其含义是正确的。

相关问题