Rails单选按钮选项哈希

时间:2013-02-14 19:23:51

标签: ruby-on-rails ruby-on-rails-3

我的观点:

<%= radio_button_tag "recommendation_ratings[#{rec.recommendation.id}][rating]", '3'%>

在我的控制器中,我解析了这些值:

 input = params[:recommendation_ratings].values
 input.each do |mini_params|
 rating = mini_params[:rating]
 recommendation_id = mini_params[:recommendation_id]

使用评级变量我在同一个控制器动作中创建一个新记录:

rate = Rating.new(
    :rating => rating,
    :label => rating_label)

如何在创建新记录时为rating_label分配评级。示例:

if rating == 1 rating_label = "Fair"

我应该在我的控制器中执行此操作,还是可以将rating_label添加到我的radio_button_tag作为另一个属性?

更新

我在我的控制器中尝试了一个case语句,但得到NoM​​ethodError“Undefined Method Rating”

 rating case
      when rating == 1
        rating_label = "Bad"
      when rating == 2
        rating_label = "Fair"
      when rating == 3
        rating_label = "Good"
      else rating == 0
        rating_label = "N/A"
      end

1 个答案:

答案 0 :(得分:2)

将您的视图代码重构为使用radio_button_tagfields_for块:

<%= fields_for :recommendation_ratings do |f| %>
  <% f.hidden_field :id, rec.recommendation.id %>
  <% f.radio_button :rating, 3 %>
<% end %>

将您的控制器代码更改为:

selected_rating = params[:recommendation_ratings]
rating = selected_rating[:rating]
recommendation_id = selected_rating[:id]

并在某处添加辅助方法:

def rating_label(rating)
  %w{N/A Bad Fair Good}[rating.to_i]
end

现在你可以创建一个新的Rating对象:

rate = Rating.new(
  :rating => rating,
  :label => rating_label(rating))