Rails Has_many 和 Belongs_to 中的模型关联

Model Associations in Rails Has_many and Belongs_to

菜单项

class MenuItem < ActiveRecord::Base
  has_many :menu_tags
end

菜单标签

class MenuTag < ActiveRecord::Base
  belongs_to :menu_item
end

迁移:

class CreateMenuItems < ActiveRecord::Migration
  def change
    create_table :menu_items do |t|
      t.string :name
      t.string :description
    end
  end
end


class CreateMenuTags < ActiveRecord::Migration
  def change
    create_table :menu_tags do |t|
      t.string :name
      t.integer :menu_item_id

      t.timestamps null: false
    end
  end
end

如果我 运行 查询某个菜单项,我该如何更改此迁移,我可以看到与其关联的所有菜单标签?所需查询:

MenuItem.first = #<MenuItem id: 2, name: "Steak", description: "Shank, medium-rare", menu_tags = [#<MenuTag id: 1, name: "Spicy">, #<MenuTag id: 4, name: "Salty">], created_at: "2016-07-18 02:54:55", updated_at: "2016-07-18 02:54:55">

已经有了 ActiveRecord,您可以通过调用类似以下内容来查看所有关联的模型:

MenuItem.first.menu_tags

问题是,对于上述内容,数据库查询可能不够高效。为了解决这些 ActiveRecord 提供了 eager_load 关联的方法:

MenuItem.includes(:menu_tags).first.menu_tags

从 ActiveRecord/Database 的角度来看,这更有效。

您会很快观察到的一件事是,当您调用以下命令时,关联的模型未显示在您的控制台中:

MenuItem.first = #<MenuItem id: 2, name: "Steak", description: "Shank, medium-rare", menu_tags = [#<MenuTag id: 1, name: "Spicy">, #<MenuTag id: 4, name: "Salty">], created_at: "2016-07-18 02:54:55", updated_at: "2016-07-18 02:54:55">

这是因为 ActiveRecord#inspect 方法的默认行为是显示模型的属性,而不添加关联模型的属性。你可以look this up in the source code here..

注意:您可以通过覆盖此 inpect 方法以包含关联对象来定义自己的行为。

希望对您有所帮助。