ActiveRecord查询帮助

时间:2010-07-12 14:32:43

标签: ruby-on-rails activerecord

我需要一点AR查询帮助。这就是我的模型的样子:

class User < AR:B
  has_many :publications
end

class Publication < AR:B
  belongs_to :user
  belongs_to :category
end

class Category < AR:B
  has_many :publications
end

现在假设我想迭代所有现有类别,并显示用户的出版物,或者显示类似“#{current_user.name}此类别中没有出版物”的内容。

class PublicationsController < AC:B

  def index
    @categories = Category.find(:all, :include => :publications, :conditions => { 'publications.user_id' => current_user })
  end

end

这为我提供了用户实际拥有出版物的所有类别,但缺少“空”的类别。

有什么建议吗? : - )

2 个答案:

答案 0 :(得分:0)

这为您提供了所有类别对象:

@categories = Category.all

然后,如果您通过关联声明has_many:您可以执行以下操作:

@categories.each do |category|
  if category.users.include?(current_user)
    # User has publications
    publications = category.publications.select { |pub| pub.user == current_user }
  else
    # User has no publications
  end
end

(has-many-through声明:

class User < AR:B
  has_many :publications
  has_many :categories, :through => :publication
end

class Publication < AR:B
  belongs_to :user
  belongs_to :category
end

class Category < AR:B
  has_many :publications
  has_many :users, :through => :publication
end

...警告:drycode)

尽管如此,使用命名范围可能还有一种更简洁的方法。

答案 1 :(得分:0)

您可以只修改查找呼叫:

@categories = Category.find(:all, :include => :publications, :conditions => [ 'publications.user_id=? OR publications.user_id IS NULL', current_user ])

请注意,我们在此使用Array变体而不是Hash变体,因为文档中的示例暗示这是正确的用法。

相关问题