Home > front end >  Rails: How do I access attributes of associated records in nested form?
Rails: How do I access attributes of associated records in nested form?

Time:11-23

I have a model availability that has a collection of days.

Each day has a name.

availability accepts nested attributes for days:

class AvailabilitiesController < ApplicationController
  before_action :require_login

  def new
    @availability = current_user.create_availability

    Date::DAYNAMES.each do |day_name|
      @availability.days << Day.new(name: day_name)
    end
  end
end

This form shows the name of each day in a text input:

<%= form_with model: @availability, local: true, url: { action: "create" } do |form| %>
  <%= form.fields_for :days, @day do |day_form| %>
    <%= day_form.text_field :name %>
  <% end %>
  <%= form.button :submit %>
<% end %>

I don't want a text field, I just want to display the day name. Something like:

<%= form_with model: @availability, local: true, url: { action: "create" } do |form| %>
  <%= form.fields_for :days, @day do |day_form| %>
    <h2><%= @day.name %></h2>
  <% end %>
  <%= form.button :submit %>
<% end %>

The above example does not work as the value of @day is nil. How do I access the name of each day?

CodePudding user response:

You don't need to pass the second argument to fields_for:

<%= form_with model: @availability, local: true, url: { action: "create" } do |form| %>
  <%= form.fields_for :days do |day_form| %>
    <h2><%= day_form.object.name %></h2>
  <% end %>
  <%= form.button :submit %>
<% end %>

This will call the days method on the object wrapped by the form builder (@availability). Passing the second argument is only ever needed if you want to overide this behavior.

Depending on what inputs you want you might not even need to use fields_for in the first place though. If you just want let the users select the days of the week you could just use the collect helpers. Fields for is only really relevant if you want to create separate inputs for the nested record such as the hours per day.

CodePudding user response:

Assuming you want to display all the days which belongs to given @availability.

The object method of the form builder instance returns the corresponding model's object. Once you get the object then you can access the model methods and attributes.

<%= form_with model: @availability, local: true, url: { action: "create" } do |form| %>
  <%= form.fields_for :days do |day_form| %>
    <h2><%= day_form.object.name %></h2>
  <% end %>
  <%= form.button :submit %>
<% end %>

Hope this works for you!

  • Related