-2

I am trying to get the id of a newly created row in a database table so that I can use it later. But it does not get passed it stays only in the viewer. I need that id after the tab or window is closed. I know there may be other ways of finding that row's id but due to some changes the website will have it needs to be done by using the id.

When the viewer is accessed it goes through a few ruby on rails statements.

<% 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 %>

It was recommended to me to use hidden_field_tag to get the integer but I can't get it to work.

Its supposed to be able to use the integer once the window is closed. Once the window is closed the following function is executed.

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 is created right there in the views while get_int and attendance_log are created in the unload function.

Anand Bait
  • 181
  • 11
roi
  • 7
  • 2
  • 1
    Try https://stackoverflow.com/questions/13672155/passing-parameters-from-view-to-controller . You can find many more on SO. – iGian Aug 12 '20 at 22:20

1 Answers1

0

A few things to be considered here:

  1. It is not a good practice to create a record on view. (@att_record.save)
  2. In hidden_field_tag you are finding value (@att_record.id) even before the record is created. So its value will be nil
  3. The value of passed attribute can be found in controller in params.

Just a quick fix to the problem mention is: Set hidden field after save.

  <% @att_record.save %>
  <%= hidden_field_tag :attr_record_id, :value => @att_record.id %>

Access it in controller as

@attendance_log = Attendance.find_by(id: params[:attr_record_id])

Note: I strongly recommend to create record with proper controller flow and not on view.

Anand Bait
  • 181
  • 11
  • Tried using the the hidden_field_tag the way it was shown to me here and it does not get stored. To test it out after using the method I use print "val = #{params[:attr_record_id]}" and get nothing in the params place. I even tested it out with other params and they do get display but this one does not. – roi Aug 13 '20 at 23:29