我使用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.joins("INNER JOIN categories ON categories.id = recipes.category_id").includes("category")
但是结果只给我来自配方表的结果。结果是:
Recipe id: 1, title: "ababa", resume: nil, created_at: "2018-02-07 23:16:19", updated_at: "2018-02-07 23:16:19", category_id: 9
如何让两个表中的数据全部显示出来?
最佳答案
你可以使用
recipes = Recipe.includes(:category) # Get all recipes and their categories
recipe = Recipe.includes(:category).find_by(id: 1) # Get one recipe with id = 1
包含不是强制性的,但会进行急切加载。
然后你就可以处理一个或多个食谱。对于特定的食谱,您可以获得类别。
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 的回答几乎没问题,但第一个语句返回一个配方数组(其中返回许多对象),而不是唯一的配方。这就是为什么您无法获取该类别的原因。
关于ruby-on-rails - 选择不同的表字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675498/