0

我的观点:

<%= 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]

使用 rating 变量,我在同一个控制器操作中创建了一个新记录:

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

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

if rating == 1 rating_label = "Fair"

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

更新:

我在控制器中尝试了 case 语句,但得到了 NoMethodError "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
4

1 回答 1

2

将您的视图代码从 using 重构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))
于 2013-02-14T19:47:53.277 回答