Ruby on rails 选择不同的表字段

Ruby on rails 选择不同的表字段,ruby-on-rails,ruby-on-rails-4,activerecord,Ruby On Rails,Ruby On Rails 4,Activerecord,我使用Rails4和mysql。我有两个配方和类别模型 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 belon

我使用Rails4和mysql。我有两个配方和类别模型

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
配方字段包括:id、标题、简历和类别id,这是类别的参考

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
类别字段包括:id和名称

我试图通过Recipe表进行查询,结果得到两个表的所有字段。我正试图通过以下查询执行此操作:

Recipe.JOIN在categories.id上加入类别= recipes.category\u id.IncludeCategory

但是结果只给出了配方表的结果。结果是:

配方id:1,标题:ababa,简历:无,创建时间:2018-02-07 23:16:19,更新时间:2018-02-07 23:16:19,类别id:9

如何显示这两个表中的所有数据?

您可以使用includes预加载关联数据,以便

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

从Subash中更正一点

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

recipes = Recipe.includes(:category) # Get all recipes and their categories
recipe = Recipe.includes(:category).find_by(id: 1) # Get one recipe with id = 1
include不是强制性的,但会进行快速加载

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

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给出的答案几乎可以,但第一条语句返回一个配方数组,其中返回许多对象,而不是唯一的配方。这就是您无法获取类别的原因。

当我使用Recipe时。包括:类别我有以下表页:ActiveRecord::AssociationNotFoundError:在Recipe上找不到名为“categories”的关联;也许你拼错了?你能再试一次吗?如果输入错误,应该是菜谱。包括:类别当我尝试菜谱时。包括:类别我有:[]>,我无法从类别表中获取数据。。。只有收件人您已经在结果对象中加载了类别数据,只需执行result.categoryhumm。。。现在我明白了。。。但当我尝试recipe.category时,我得到:nomethoderor:recipe Load 0.2ms选择recipes.*来自recipes LIMIT?[[LIMIT,11]]类别加载0.4ms从类别中选择类别。*其中categories.id=9未定义的方法“Category”用于FROM irb:94
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