【问题标题】:Form passes attribute which is not part of the model as param表单将不属于模型的属性作为参数传递
【发布时间】:2014-09-16 16:28:10
【问题描述】:

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

[“免费”、“$1”、“$2”]

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

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

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

通过故障排除,我意识到 params[:donation] 为 nil,而不是“$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'

【问题讨论】:

  • 您到底需要什么? - 您需要将所选值转换为 int 吗?
  • 您是否允许控制器中的:donation 参数?
  • 当我将 :donation 添加到允许的参数列表时,它抛出了一个错误,因为它不是门票的实际属性。
  • @KevinM 你能发布你的日志吗?也可以通过js在客户端处理,去掉value中的“$”。
  • 我应该在日志的哪一部分寻找你想看的,@Mandeep?

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


【解决方案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>

并将参数提交为:

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

【讨论】:

  • 我想出了一个替代方案,但我更喜欢你的解决方案。
猜你喜欢
  • 1970-01-01
  • 2011-08-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-06-21
  • 1970-01-01
相关资源
最近更新 更多