gpt4 book ai didi

ruby-on-rails - Rails 3,使用单选按钮标签进行 DRY 的最佳方式?

转载 作者:行者123 更新时间:2023-12-02 00:35:21 25 4
gpt4 key购买 nike

假设一个名为“favfood”的整数字段,我们将单选按钮选项表示为

0 indicates "no favorite"
1 indicates "Wine and cheese"
2 indicates "Burger with everything"

在我们的 _edit View 中,我们显示带有上面友好标签的单选按钮

在/show View 和/index View (以及其他几个地方)上,当我们显示用户偏好时,我们会显示相同的相应长文本。

在 _edit 中将文字字符串放在每个单选按钮旁边,然后提供一些逻辑以根据当前值在/show 和/index 等上显示相同的文字字符串,这似乎不是 DRY。

此外,我们必须重复使用相同的逻辑,即如果值 = 1 则显示“第一选择”,如果值 = 2 则显示“第二选择”。

处理 radio 标签的用户友好标签的“rails 方式”是什么,以便标签(及其与字段值的关联)定义一次?

最佳答案

有两件事你应该做。一种使用国际化 (I18n),以便您的文本存储在您的 en.yml 文件中,您可以使用标签而不是字符串:

# en.ymlen:  no_favorite: 'No favorite'  wine_and_cheese: 'Wine and Cheese'  burger_with_everything: 'Burger with everything'# You can then translate the labels like thisI18n.t :no_favoriteI18n.t :wine_and_cheeseI18n.t :burger_with_everything

下一步是创建某种哈希或类来为您存储和转换整数值。一个简单的数组解决方案可能如下所示:

OPTIONS = [:no_favorite, :wine_and_cheese, :burger_with_everything]

然后您可以使用这样的选项:

selected_value = 1I18n.t OPTIONS[selected_value] # => wine_and_cheeseOPTIONS.index :wine_and_cheese # => 1

此外,如果所选选项是模型值(例如 User#food_preference),您可以定义一个函数来显示该用户的食物偏好:

class User  OPTIONS = [:no_favorite, :wine_and_cheese, :burger_with_everything]  def display_food_preference    I18n.t OPTIONS[food_preference]  endend

关于ruby-on-rails - Rails 3,使用单选按钮标签进行 DRY 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4881811/

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