表单传递属性,它不是模型的一部分作为参数

时间:2014-09-16 16:28:10

标签: ruby-on-rails forms ruby-on-rails-4 parameters controller

我有一个包含货币值下拉列表的表单,例如:

["免费"," $ 1"," $ 2"]

结果作为参数传递给控制器​​:捐赠。但我需要将此字符串(例如" $ 1")转换为整数,以便将其保存在属性中的模型中:donation_per_ticket。

下拉列表中的值将传递给控制器​​。但是当我尝试在控制器中使用类似的东西时,它不起作用:

@ticket.donation_per_ticket = ["Free", "$1", "$2"].index(params[:donation])

通过故障排除,我意识到params [:捐赠]是零,而不是" $ 1"。我是否试图错误地引用参数或控制器忽略参数?

我在rails 4上使用ruby并且我使用simple_form gem来创建表单。

从开发中记录

Started POST "/performances/15/tickets" for 127.0.0.1 at 2014-09-16 14:41:25 -0500
Processing by TicketsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"xh4h5PKgjjE8hKv0NxXwoBMui6nNB9Wf9ecfMh/1eaU=", "ticket"=>{"performance_id"=>"", "user_id"=>"1", "status"=>"pending", "access_key"=>"9dfd37c27d6994e919e587fbe087d345", "name"=>"jjj", "email"=>"info@undertheguntheater.com", "quantity"=>"1", "donation_per_ticket"=>"$12"}, "commit"=>"Reserve tickets", "performance_id"=>"15"}
  Performance Load (0.3ms)  SELECT  "performances".* FROM "performances"  WHERE "performances"."id" = ?  ORDER BY start_time ASC LIMIT 1  [["id", 15]]
  Show Load (0.4ms)  SELECT  "shows".* FROM "shows"  WHERE "shows"."id" = ? LIMIT 1  [["id", 3]]
  User Load (0.3ms)  SELECT  "users".* FROM "users"  WHERE "users"."id" = 1  ORDER BY full_name ASC LIMIT 1
Unpermitted parameters: donation_per_ticket
  Performance Load (0.2ms)  SELECT  "performances".* FROM "performances"  WHERE "performances"."id" = ?  ORDER BY start_time ASC LIMIT 1  [["id", 15]]
Completed 500 Internal Server Error in 220ms

NoMethodError (undefined method `[]' for nil:NilClass):
  app/controllers/tickets_controller.rb:67:in `create'

1 个答案:

答案 0 :(得分:1)

您可能希望渲染下拉列表,以便将整数值作为参数传递,而不是人性化值。

由于您提到您正在使用simple_form,因此您可以在表单中执行以下操作:

<%= f.input :donation do %>
  <%= f.select :donation, [["Free", 0], ["$1", 1], ["$2", 2]] %>
<% end %>

将html呈现为:

<select id="ticket_donation" name="ticket[donation]">
  <option value="0">Free</option>
  <option value="1">$1</option>
  <option value="2">$2</option>
</select>

并将params提交为:

# log file
Parameters: {"ticket"=>{"donation"=>"1"}}