0

私はモデル記事を持っています

class Article
  include Mongoid::Document
  has_and_belongs_to_many :categories, inverse_of: nil
end

そして私はモデルカテゴリを持っています

class Category
  include Mongoid::Document
  field :name, type: String  
end

、などAuthorの名前のカテゴリがいくつかあります。私はこれを試します:SecurityMobilecategory.name == 'Author'

Article.where(categories: [name: 'Author'])

しかし、うまくいきません。

4

2 に答える 2

2

次のクエリを使用するだけです。

category = Category.where(:name => 'Author').first
articles = category.articles
于 2013-10-24T07:11:18.267 に答える
1

has_and_belongs_to_many は nn 関係を意味するため、そのように照会したい場合は逆関係が本当に必要です。

class Article
  include Mongoid::Document
  has_and_belongs_to_many :categories
end

class Category
  include Mongoid::Document
  field :name, :type => String
  has_and_belongs_to_many :articles
end

今、あなたはこれを行うことができます:

Category.where(:name => 'Author').first.articles

または、記事自体の配列にカテゴリを格納することもできます

class Article
  include Mongoid::Document
  field :categories, :type => Array, :default => []
end

次に、これを行うことができます

Article.in(:categories => 'Author')

モデルを本当に変更できない場合は、これを試してください。

author_category = Category.where(:name => 'Author').first
Article.in(:category_ids => author_category.id)
于 2013-10-24T07:18:54.820 に答える