【问题标题】:Conditionally setting html parameters in Rails在 Rails 中有条件地设置 html 参数
【发布时间】:2016-02-08 21:42:12
【问题描述】:

我有一对单选按钮,我想将 checked 值预分配给我的 new 操作。现在我有条件地渲染两个部分。一个部分包含带有 checked 属性的单选按钮,而另一个部分完全没有属性:

<%= form_for([@restaurant, @dish_review], url: :restaurant_dish_reviews) do |f| %>
  <% if action_name == "new" %>
    <%= render "status_buttons_checked", f: f, dish: @dish %>
  <% else %>
    <%= render "status_buttons", f: f %>
  <% end %>
<% end %>

_status_buttons_checked

<div class="field">
    <%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on?(dish) %>
    <%= f.label :status, value: :upvoted %>

    <%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on?(dish) %>
    <%= f.label :status, value: :downvoted %>
</div>

_statsus_buttons

<div class="field">
    <%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on?(dish) %>
    <%= f.label :status, value: :upvoted %>

    <%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on?(dish) %>
    <%= f.label :status, value: :downvoted %>
</div>

我想知道 Rails 中是否有任何方法可以在 radio_button 参数中插入条件而不是创建两个部分。我想要类似于下面显示的内容,但遇到模板错误:

<%= f.radio_button :status, :downvoted, if action_name == "new" current_user.voted_down_on?(dish) %>

【问题讨论】:

    标签: html ruby-on-rails parameters radio-button conditional


    【解决方案1】:

    使用form_for 时,您使用的表单方法会自动填充适合您属性的数据。虽然我不知道这是否适用于 checked 值,但这意味着如果您有以下情况:

    <%= form_for @user do |f| %>
       <%= f.text_field :name %>
    <% end %>
    

    ...:name 将从您的 @user 对象中填充(如果是 new,则不会插入任何数据)。

    --

    这意味着如果您使用form_for,您应该能够使用传递给视图的数据填充checked 值:

    <%= form_for [@restaurant, @dish_review] do |f| %>
       <%= f.radio_button :status, :upvoted, checked: current_user.voted_up_on? @dish %>
       <%= f.radio_button :status, :downvoted, checked: current_user.voted_down_on? @dish %>
    <% end %>
    

    我看不出你想从你的部分实现什么(它们都是相同的)——但如果你想在条件下创建“检查”,你可以使用以下内容:

       <%= checked = action_name == "new"
       <%= f.radio_button :status, :downvoted, checked: checked %>
    

    这将根据操作是否为new 将值设置为“true”或“false”。

    【讨论】:

      猜你喜欢
      • 2022-12-11
      • 2015-03-01
      • 1970-01-01
      • 2019-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-07
      相关资源
      最近更新 更多