gpt4 book ai didi

ruby-on-rails - 如何在Rails的 Controller 方法中传递变量以呈现

转载 作者:行者123 更新时间:2023-12-04 06:19:20 28 4
gpt4 key购买 nike

我试图传递一个变量来呈现这样的:

def monitor
@peripheries = Periphery.where('periphery_type_name=?','monitor')
render 'index', type: 'Monitor'
end

在这里我想在索引 View 中使用'type'变量,如下所示:
<%= render 'some_partial', periphery_type: type %>

这也带来了一些东西。但是我想使用那个'type'变量

最佳答案

有两种方法可以在 Controller 和 View 之间传递变量:
实例变量

def monitor
@peripheries = Periphery.where('periphery_type_name=?','monitor')
@type = 'Monitor'
render 'index'
end

Rails会将属于 Controller 的任何实例变量导出到 View 上下文。因此,您可以在 View 或任何局部 View 中调用 @type
本地人
def monitor
@peripheries = Periphery.where('periphery_type_name=?','monitor')
render 'index', locals: { type: 'Monitor' }
end
请注意,您需要将哈希传递给 locals选项。您还需要将局部变量传递给局部 View :
<%= render 'some_partial', locals: { periphery_type: type } %>
使用本地人通常是一个好主意,因为它会鼓励去耦,并且可以使您的片段更可重用。

关于ruby-on-rails - 如何在Rails的 Controller 方法中传递变量以呈现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30693677/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com