RoR form_for:隐藏字段未包含在对象参数中,因此不起作用。
我正在使用表单添加条目,并且需要发送当前用户的 ID 以及条目参数。这是我的表单代码:
<% form_for(@entry) do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'user_id', current_user.id %>
<p>
<%= f.label :date %><br />
<%= f.date_select :date %>
</p>
<p>
<%= f.label :note %><br />
<%= f.text_field :note %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
问题是 user_id 被保存为 null。我注意到下面的控制台输出中存在 user_id,但它实际上并不位于条目对象参数内。我该如何解决这个问题?感谢您的阅读。
Processing EntriesController#create (for 127.0.0.1 at 2010-07-09 19:57:55) [POST]
Parameters: {"commit"=>"Create", "action"=>"create", "user_id"=>"3", "entry"=>{"date(1i)"=>"2010", "date(2i)"=>"7", "date(3i)"=>"9", "note"=>"bb"}, "controller"=>"entries"}
Entry Create (0.4ms) INSERT INTO "entries" ("entry_id", "created_at", "updated_at", "date", "user_id", "note") VALUES(NULL, '2010-07-09 09:57:55', '2010-07-09 09:57:55', '2010-07-09', NULL, 'bb')
Redirected to http://localhost:3000/entries/7
Completed in 24ms (DB: 0) | 302 Found [http://localhost/entries]
I'm using a form to add an entry, and I need to send the id of the current user along with the entry parameters. Here is my form code:
<% form_for(@entry) do |f| %>
<%= f.error_messages %>
<%= hidden_field_tag 'user_id', current_user.id %>
<p>
<%= f.label :date %><br />
<%= f.date_select :date %>
</p>
<p>
<%= f.label :note %><br />
<%= f.text_field :note %>
</p>
<p>
<%= f.submit 'Create' %>
</p>
<% end %>
The problem is that user_id is being saved as null. I noticed in the console output below that user_id is present, but it isn't actually located within the entry object parameters. How can I fix this? Thanks for reading.
Processing EntriesController#create (for 127.0.0.1 at 2010-07-09 19:57:55) [POST]
Parameters: {"commit"=>"Create", "action"=>"create", "user_id"=>"3", "entry"=>{"date(1i)"=>"2010", "date(2i)"=>"7", "date(3i)"=>"9", "note"=>"bb"}, "controller"=>"entries"}
Entry Create (0.4ms) INSERT INTO "entries" ("entry_id", "created_at", "updated_at", "date", "user_id", "note") VALUES(NULL, '2010-07-09 09:57:55', '2010-07-09 09:57:55', '2010-07-09', NULL, 'bb')
Redirected to http://localhost:3000/entries/7
Completed in 24ms (DB: 0) | 302 Found [http://localhost/entries]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
其他答案是为 Rails 2 编写的。Salil 答案的 Rails 3 改编使用以下格式:
The other answers are written for Rails 2. The Rails 3 adaptation of Salil's answer uses this format:
使用
而不是
解释:-
在控制器中,您可能会执行以下操作,
因此您必须执行以下操作之一(除了我上面提到的一个)
或
USE
INSTEAD OF
Explaination:-
In controller probably you doing something like follwing
So you have to one of the following (othere than one i mention above)
or
对于 Rails 4 使用:
For Rails 4 use:
将隐藏字段包含在表单生成器对象“f”中
include the hidden field with your form builder object 'f'