我有一个设置条目的表。我想在我的模型和控制器中将这些条目作为变量访问,而无需每次都查询数据库来设置这些变量。
我可以通过为我的模型和控制器创建重复的“关注点”来让它工作。我还可以在我的 ApplicationController 中设置全局变量。或者我可以在我需要它们的每个地方初始化它们。设置和访问可以在控制器和模型中访问的全局变量的正确 rails 方法是什么?
class ItemType
has_many :items
end
class Item
belongs_to :item_type
belongs_to :foo
end
class Foo
has_many :items
def build_item
bar_item_type = ItemType.find_by(:name => "bar")
self.items.build(
:foo_id => self.id,
:item_type_id => bar_item_type.id
)
end
end
class ItemsController
def update
bar_item_type = ItemType.find_by(:name => "bar")
@item.update(:item_type_id => bar_item_type.id)
end
end
在示例中,您可以看到我bar_item_type
在 Foo 模型和 ItemsController 中都声明了变量。我想通过能够为我的 rails 项目创建和访问该变量一次来干掉我的代码库,而不必在任何地方进行相同的数据库调用。