在我的网站上,我有卡片,点击“美国”按钮时需要弹出的卡片和点击“欧洲”按钮时需要出现的卡片。除了最后一部分,我编码了所有内容。如果我在控制器的 index 方法中输入它,则只会出现美国卡:
def index
@foods = Food.usa
end
如果我输入这个:
def index
@foods = Food.europe
end
只弹出欧洲卡。我希望能够通过在我的网站上单击一个简单的按钮来做到这一点。我怎么做?
我的按钮代码
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="options" id="europe" autocomplete="off" checked> Europe
</label>
<label class="btn btn-primary">
<input type="radio" name="options" id="usa" autocomplete="off"> USA
</label>
</div>
我的控制器的名字是food_controller.rb
感谢你们对我的帮助。
您可以使用单选按钮的值将参数发送到您的控制器,该值将是usa
或europe
然后您可以使用send
方法动态调用usa
或europe
在您的Food
模型上。
例如,您food_name
从前端向控制器发送了一个参数。
你的代码看起来像这样
def index
@foods = Food.send(params[:food_type].to_sym)
end
但是在直接使用来自用户的参数时要小心,因为它可能会破坏您的应用程序。
一种安全的方法是在您的控制器中创建一系列可能的食物类型。
像这样的东西:
SUPPORTED_FOOD_TYPES = ["usa", "europe"].freeze
然后在你的控制器中你会这样做
def index
@foods = Food.send(food_type.to_sym)
end
def food_type
if SUPPORTED_FOOD_TYPES.include? params[:food_type]
params[:food_type]
else
'all'
end
end
您的 html 代码将如下所示:
<%= form_tag(foods_path, method: "get") do %>
<div class="btn-group btn-group-toggle" data-toggle="buttons">
<label class="btn btn-primary active">
<input type="radio" name="food_type" value="europe" id="europe" autocomplete="off" checked> Europe
</label>
<label class="btn btn-primary">
<input type="radio" name="food_type" value="usa" id="usa" autocomplete="off"> USA
</label>
</div>
<input type="submit" value="Apply">
<% end %>
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句