Ruby 关于 Rails:如何 return 来自查询的值集合(或数组)
Ruby On Rails: how to return a collection (or array) of values from a query
我有一个名为 FORMS
的父 table,它在 ROR 中有许多 ITEMS
,而 ITEMS
属于 FORMS
。我需要从 ITEMS
中获取属于 FORMS
table 中最后一个条目的数量值。
form.rb
class Form < ApplicationRecord
has_many :items
end
item.rb
class Item < ApplicationRecord
belongs_to :form
end
Rails 控制台
2.3.1 :024 > Form.last.items.quantities
Form Load (0.6ms) SELECT `forms`.* FROM `forms` ORDER BY `forms`.`id` DESC LIMIT 1
NoMethodError: Item Load (0.3ms) SELECT `items`.* FROM `items` WHERE `items`.`form_id` = 63
undefined method `quantities' for...
更高效的内存方式:
Form.last.items.pluck(:quantity)
我有一个名为 FORMS
的父 table,它在 ROR 中有许多 ITEMS
,而 ITEMS
属于 FORMS
。我需要从 ITEMS
中获取属于 FORMS
table 中最后一个条目的数量值。
form.rb
class Form < ApplicationRecord
has_many :items
end
item.rb
class Item < ApplicationRecord
belongs_to :form
end
Rails 控制台
2.3.1 :024 > Form.last.items.quantities
Form Load (0.6ms) SELECT `forms`.* FROM `forms` ORDER BY `forms`.`id` DESC LIMIT 1
NoMethodError: Item Load (0.3ms) SELECT `items`.* FROM `items` WHERE `items`.`form_id` = 63
undefined method `quantities' for...
更高效的内存方式:
Form.last.items.pluck(:quantity)