在不更新模型轨道的情况下更新实例变量



我有以下模型。。。

ItemAttribute(id: integer, name: string count: integer)

在我的控制器中,我想为计数设置一个自定义金额,我可以在我的视图中使用。。。

@building = ItemAttribute.find_by_name("wall")
# the following line of code updates the model as well as the instance variable (not what I want)
@building.update_attribute(:count,10)
# the following line of code doesn't update the model (desired), but the value also resets back to the model's value in the view (not desired)...
@buildings.find_by_name("wall").count = 10

我正在视图中的循环中使用count属性。墙实例恰好是一种特殊情况,这就是为什么我只想在视图中更新属性。

您只需在控制器中设置一个实例变量,然后在视图中访问该变量。

@building = ItemAttribute.find_by_name("wall")
@count = 10

然后在您的视图中访问@count。该实例变量仅适用于请求,并且可用于控制器和视图。

不确定最后一行要做什么,它将10分配给活动记录对象列表的计数。

获得10墙

@buildings = Building.find_by_name("wall").limit(10)

要获得name=="墙"且count===10 的建筑

@buildings = Building.where(name: "wall", count: 10)

相关内容

最新更新