访问存储在 PSQL Rails 中的数组
Access an array stored in PSQL Rails
我是 Rails 的新手,希望您能帮助我。
我想访问一个数组并打印出该数组的每个元素。现在使用此代码
- @recipes.each do |recipe|
%h2= recipe.name
%p= recipe.description
%p= recipe.cuisine_id
%p= recipe.ingredients
recipe.ingredients 在浏览器上打印
当我尝试做
- recipe.ingredients.each do |ingredient|
%p= ingredient
它试图查询成分 table,而它只是 table 配方的一列。如果我使用 to_s
.
也会得到同样的结果
你有什么建议吗?
谢谢大家!
正如我所见,您的 recipes
模型中有一个 ingredients
属性,还有一个名为 ingredients
的模型,也许您可以尝试 "aliasing" recipe.ingredients
列:
# app/models/recipe.rb
class Recipe < ApplicationRecord
...
alias_attribute :new_alias, :column_name
end
这样您就可以使用两个名称(旧名称或您设置的别名)访问该属性。
- recipe.new_alias.each do |ingredient|
%p= ingredient
您还可以 select 该列使用 ActiveRecord 的别名,例如:
@recipes = Recipe.select('description, cuisine_id, ingredient AS some_alias')
然后在你看来:
- recipe.some_alias.each do |ingredient|
%p= ingredient
您有不同的 recipe
和 ingredient
模型吗?根据您的描述,听起来食谱与配料有 has_many
关系。如果是这样,那么多个查询就完全有意义了。
基本上,当您尝试访问尚未加载的模型时,Rails 会为您执行查询。如果您没有在视图中包含正在访问的内容,这可能会很麻烦,而且调试起来会很困难。您需要做的是在您的控制器中查找食谱的 .joins(:ingredients)
,它将在您加载食谱时加载相关的成分。没有看到你的控制器和模型代码,我不能更具体。
我是 Rails 的新手,希望您能帮助我。
我想访问一个数组并打印出该数组的每个元素。现在使用此代码
- @recipes.each do |recipe|
%h2= recipe.name
%p= recipe.description
%p= recipe.cuisine_id
%p= recipe.ingredients
recipe.ingredients 在浏览器上打印
当我尝试做
- recipe.ingredients.each do |ingredient|
%p= ingredient
它试图查询成分 table,而它只是 table 配方的一列。如果我使用 to_s
.
你有什么建议吗?
谢谢大家!
正如我所见,您的 recipes
模型中有一个 ingredients
属性,还有一个名为 ingredients
的模型,也许您可以尝试 "aliasing" recipe.ingredients
列:
# app/models/recipe.rb
class Recipe < ApplicationRecord
...
alias_attribute :new_alias, :column_name
end
这样您就可以使用两个名称(旧名称或您设置的别名)访问该属性。
- recipe.new_alias.each do |ingredient|
%p= ingredient
您还可以 select 该列使用 ActiveRecord 的别名,例如:
@recipes = Recipe.select('description, cuisine_id, ingredient AS some_alias')
然后在你看来:
- recipe.some_alias.each do |ingredient|
%p= ingredient
您有不同的 recipe
和 ingredient
模型吗?根据您的描述,听起来食谱与配料有 has_many
关系。如果是这样,那么多个查询就完全有意义了。
基本上,当您尝试访问尚未加载的模型时,Rails 会为您执行查询。如果您没有在视图中包含正在访问的内容,这可能会很麻烦,而且调试起来会很困难。您需要做的是在您的控制器中查找食谱的 .joins(:ingredients)
,它将在您加载食谱时加载相关的成分。没有看到你的控制器和模型代码,我不能更具体。