1

试图将数据从表单保存到数据库。使用 select_tag

<%= select_tag :size, options_from_collection_for_select(@plan, 'name', 'size') %>

一切都很好,它同时获取大小和电子邮件,但是当我尝试存储表单(大小)中的数据时,它传递了 NULL。

这是我的控制台:

Started POST "/users" for 127.0.0.1 at 2011-06-24 07:25:29 -0500
Processing by UserController#create as HTML
Parameters: {"utf8"=>"✓",   "authenticity_token"=>"MfT3gs5TtR+bvpaLro0E8Qm1zojaY2ms9WK0WprKPAw=", "size"=>"small",
"user"=>{"email"=>"5@gmail.com"}, "commit"=>"Create User"}
AREL (0.4ms)  INSERT INTO "users" ("email", "size", "created_at", "updated_at") VALUES
 ('5@gmail.com', NULL, '2011-06-24 12:25:29.646814', '2011-06-24 12:25:29.646814')
Redirected to http://localhost:3000/users/14
Completed 302 Found in 56ms

因此,它从表单中获取正确的数据,如您所见“size”=>“small”,但是当它存储它时,它将它作为 NULL 传递,

 VALUES ('5@gmail.com', NULL, '2011-06-24

我想,这是 select_tag,因为它没有附加你,就像 text_field 一样

<%= form_for @user do |u| %>
                    <%= render 'shared/error_messages' %>
                        <p><%= u.label :size, 'How many employees do you have?' %>: </p>
                        <p><%= select_tag :size, options_from_collection_for_select(@plan, 'name', 'size') %></p>

                        <p><%= u.label :email, 'What\'s your email address?' %>:</p>
                        <p><%= u.text_field :email %></p>
                        <%= u.submit%>
                    <% end %>

但是当我尝试 u.select_tag = Error, undefined 方法时。

我的模型

  class User < ActiveRecord::Base
attr_accessible :size, :email
end

有什么想法吗?

4

1 回答 1

1

您需要将“大小”参数嵌套在“用户”哈希中。当您查看日志时,您想验证是否看到如下内容:

"user"=>{"email"=>"5@gmail.com", "size"=>"small"}

要在表单内部实现这一点,您可以保留现有的 select_tag 并将其范围设置为:

<%= select_tag 'user[size]', options_from_collection_for_select(@plan, 'name', 'size') %>

或者,对于这种情况,您似乎可以在表单对象上使用 collection_select 范围:

<%= u.collection_select :size, @plan, :name, :size %>
于 2011-06-24T14:11:00.177 回答