Jon Girard Jon Girard - 11 months ago 49
Ruby Question

Output record id through form builder nested form

I have a model called "loans", which has many :vehicles. The model implementation for loan accepts nested attributes for vehicles through a nested form (provided through simple_form gem).

class Loan < ApplicationRecord
has_many :vehicles
accepts_nested_attributes_for :vehicles


class LoansController < ApplicationController

def new
@loan =

def edit
@loan = Loan.find(params[:id])
@vehicle = @loan.vehicles


<%= simple_form_for @loan, :html => {:class => "loan-edit-form"} do |f| %>
<%= f.simple_fields_for :vehicles do |vehicle| %>
<%= render 'vehicle_fields_edit', :f => vehicle %>
<% end %>
<% end %>


<div class="nested_vehicle" data-id="<%= %>">
<%= f.hidden_field :id, id: "vehicle_id", name: "vehicle_id" %>
<div class="divider-top"></div>
<div class="vehicle-number">
Vehicle <span class="vehicle-count-rails"><%= f.index + 1 %></span>
...... etc

The problem is I'm unable to show the database record ID of the vehicle in the edit nested form as I'm trying to do in the "data-id" attribute since I'm using simple form builder and not simply looping through the loan records using
@loan.vehicles.each do |vehicle|

Using a hidden field I'm able to show the record ID, however, it is shown within an input form field item, whereas I need to retrieve only the ID value alone for use within the data-id attribute.

I've tried
<%= %>
but get a form builder error. How can I get the record ID whilst using form builder as I've described?

Answer Source

Try this, instead of

<%= %>