Q:

Rails/Ruby - Prepopulate form with data passed from another page

How do I get values to prepopulate a new device form when navigating to it from rfid partial of view/cabinet/show page?  device has_one rfid.
The link from cabinet/show:
<%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, cabinet_id: @cabinet.id}), :class => "btn btn-primary" %>

The devices_controller, I want to have the create method work when either 0 or 2 params are passed:
def create(options)

if options[:cabinet_id] and options[:id]
  @rfid = Rfid.find(params[:id])
  @device = Device.new(params[:device])
  @device.rfid = @rfid
  @device.cabinet_id = :cabinet_id

else
  @device = Device.new(params[:device])
  @cabinet = Cabinet.find(params[:device][:cabinet_id])
  @device.row_id = @cabinet.row_id
end
  respond_to do |format|
    if @device.save and @cabinet.refresh_capacity_used and @cabinet.refresh_consumption
      format.html { redirect_to @device, notice: 'Device was successfully created.' }
      format.json { render json: @device, status: :created, location: @device }
    else
      format.html { render action: "new" }
      format.json { render json: @device.errors, status: :unprocessable_entity }
    end
  end

end
The cabinet_id and rfid portion of new device/_form:
<tr>
        <th>Cabinet</th>
        <td><%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", @device.cabinet_id) %></td>
</tr>

<tr>
        <th>RFID</th>
        <td><%= f.text_field :rfid, :value => params[:rfid]%></td> 
</tr>

Thank you.

A:

If you have:
<%= link_to "Create New Device (non-functional)", new_device_path({:id => @rfid.id, :cabinet_id => @cabinet.id}), :class => "btn btn-primary" %>

you can get prepopulate the rfid and cabinet_id fields using:
<%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", params[:cabinet_id]) %>

<%= f.text_field :rfid, :value => params[:id] %>

Note that your params key must match the value passed into the hash in your link_to tag.

A:

@zeantsoi's answer as posted mostly works, but it breaks the editing functionality. As a fix, I propose the following minor modification:
<%= f.select :cabinet_id, options_from_collection_for_select(Cabinet.order(:name).all, "id", "name", params[:cabinet_id] || @device.cabinet_id) %>

<%= f.text_field :rfid, :value => params[:rfid] || @device.rfid %>

This way, if params[:cabinet_id] is absent, @device.cabinet_id (the existing value) will persist.

