【问题标题】:Select different table fields选择不同的表格字段
【发布时间】:2018-02-08 00:20:29
【问题描述】:

我使用 Rails 4 和 mysql。我有两个 Recipe 和 Category 模型。

class Category < ApplicationRecord
  has_many :recipes
  validates_uniqueness_of :name, message: "deve ser único"
  validates_presence_of :name, message: "can't be blank"
end

class Recipe < ApplicationRecord
  belongs_to :category
end

Recipe 字段是:id、title、resume 和 category_id,它是类别的参考。

类别字段为:id 和 name

我正在尝试通过 Recipe 表进行查询,结果是这两个表的所有字段。我正在尝试使用以下查询来做到这一点:

Recipe.joins("INNER JOIN categories ON categories.id = recipes.category_id").includes("category")

但结果只给了我来自配方表的结果。结果是:

配方 ID:1,标题:“ababa”,简历:nil,created_at:“2018-02-07 23:16:19”,updated_at:“2018-02-07 23:16:19”,category_id:9

如何让两个表中的数据全部显示出来?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 activerecord


    【解决方案1】:

    你可以使用

    recipes = Recipe.includes(:category) # Get all recipes and their categories
    recipe = Recipe.includes(:category).find_by(id: 1) # Get one recipe with id = 1
    

    includes 不是强制性的,但会进行预先加载。

    然后你可以处理一个或多个食谱。对于特定的食谱,您可以获得类别。

    catname = recipe.category.name # Name of the category of one recipe
    
    catnames = [] # Empty array
    recipes.each do |r|
      catnames << r.category.name # Add name of category to array of names
    end
    

    注意:Subash 的回答几乎没问题,但第一条语句返回一个配方数组(其中返回许多对象),而不是唯一的配方。这就是您无法获取类别的原因。

    【讨论】:

      【解决方案2】:

      你可以使用includes来预加载关联数据,所以你可以这样做

      recipe = Recipe.includes(:category).where....
      category = recipe.category
      

      【讨论】:

      • 当我使用 Recipe.includes(:categories) 时,我收到以下消息: ActiveRecord::AssociationNotFoundError: 在 Recipe 上找不到名为“categories”的关联;也许你拼错了?
      • 你能再试一次吗,打错了,应该是Recipe.includes(:category)
      • 当我尝试 Recipe.includes(:category) 我有:[#]>,我无法从类别表中获取数据...只有配方
      • 您已经在结果对象中加载了category 数据,只需执行result.category
      • 嗯……现在我明白了……但是当我尝试 recipe.category 时,我得到: NoMethodError: Recipe Load (0.2ms) SELECT "recipes".* FROM "recipes" LIMIT ? [["LIMIT", 11]] 类别负载 (0.4ms) SELECT "categories".* FROM "categories" WHERE "categories"."id" = 9 undefined method `category' for #<:activerecord_relation:0x000055ec6c6df160>来自(irb):94
      【解决方案3】:

      从 Subash 改正一点

      recipes = Recipe.includes(:category).where ...
      recipes.each do |recipe|
        # category you need is here
        category = recipe.category
      end
      

      【讨论】:

        猜你喜欢
        • 2019-10-15
        • 2021-04-23
        • 2011-01-28
        • 1970-01-01
        • 2017-03-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多