Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails RubyonRails:查找特定类别中的所有主题?_Ruby On Rails_Ruby - Fatal编程技术网

Ruby on rails RubyonRails:查找特定类别中的所有主题?

Ruby on rails RubyonRails:查找特定类别中的所有主题?,ruby-on-rails,ruby,Ruby On Rails,Ruby,我试图在一个特定类别中查找所有主题,但我不确定这是否是最有效的方法: Topic.all.select { |topic| topic.categories.include?(category) } 上面这些对我来说很有用,但是MySQL似乎需要很长时间才能找到记录。还有什么比这更有效的吗?现在听起来,当你需要一个多对多的关系时,你在主题和类别之间有一个多对多的关系。按以下方式重新构造模型: # app/models/category.rb class Category < Active

我试图在一个特定类别中查找所有主题,但我不确定这是否是最有效的方法:

Topic.all.select { |topic| topic.categories.include?(category) }

上面这些对我来说很有用,但是MySQL似乎需要很长时间才能找到记录。还有什么比这更有效的吗?

现在听起来,当你需要一个多对多的关系时,你在主题和类别之间有一个多对多的关系。按以下方式重新构造模型:

# app/models/category.rb
class Category < ActiveRecord::Base
  has_and_belongs_to_many :topics
end

# app/models/topic.rb
class Topic < ActiveRecord::Base
  has_and_belongs_to_many :categories
end
并增加以下内容:

class AddCategoriesTopicsJoinTable < ActiveRecord::Migration
  def self.up
    create_table :categories_topics, :id => false do |t|
      t.integer :category_id
      t.integer :topic_id
    end
  end

  def self.down
    drop_table :categories_topics
  end
end
class AddCategoriesTopicsJoinTablefalse do | t|
t、 整数:类别\u id
t、 整数:主题id
结束
结束
def自动关闭
下拉列表:类别主题
结束
结束
请注意,联接表是通过按字母顺序组合两个表名来命名的。这就是Rails知道如何自动找到它的方式

现在,您可以调用
@category.topics
获取主题数组,也可以调用
@topic.categories
获取类别。它在两个方向都起作用


更新:关于Rails中多对多关系的问题经常出现,因此我写了一篇文章,解释如何使用
habtm
vs
hasu-many:through
,以及它们之间的区别。

这是一个很棒的Jaime。非常感谢你!
class AddCategoriesTopicsJoinTable < ActiveRecord::Migration
  def self.up
    create_table :categories_topics, :id => false do |t|
      t.integer :category_id
      t.integer :topic_id
    end
  end

  def self.down
    drop_table :categories_topics
  end
end