问题描述
我正在尝试获取数据库表中新创建的行的ID,以便以后使用。但是它没有通过,仅停留在查看器中。标签或窗口关闭后,我需要该ID。我知道可能还有其他方法可以找到该行的ID,但是由于某些更改,网站需要使用ID来完成。
访问查看器时,它会在rails语句中经过一些红宝石。
<% if user_signed_in? %>
<% @att_record = Attendance.new(:user_id => current_user.id,:time_in => Time.now) %>
<% #@attendance_log = @att_record #tried this already,controller doesn't receive it %>
<%= hidden_field_tag :@get_int,:value => @att_record.id %>
<% @att_record.save %>
建议我使用hidden_field_tag来获取整数,但我无法使其正常工作。
一旦关闭窗口,它应该能够使用整数。关闭窗口后,将执行以下功能。
def unload
@get_int
@attendance_log = Attendance.find_by(id: get_int)
@attendance_log.time_out = Time.now
@attendance_log.save
head :ok
end
@att_record在视图中立即创建,而get_int和Attenance_log在卸载功能中创建。
解决方法
这里要考虑的几件事:
- 在视图上创建记录不是一个好习惯。 (
@att_record.save
) - 即使在创建记录之前,您也可以在hidden_field_tag中找到值(
@att_record.id
)。所以它的值为零 - 可以在控制器的params中找到传递的属性的值。
问题的快速解决方法是: 保存后设置隐藏字段。
<% @att_record.save %>
<%= hidden_field_tag :attr_record_id,:value => @att_record.id %>
在控制器中以以下方式访问
@attendance_log = Attendance.find_by(id: params[:attr_record_id])
注意:我强烈建议创建具有适当控制器流且不在视图中的记录。