'How to immediatly set a variable in a controller?

Briefly, here's my associations:

Team:     has_many   :calendars
Calendar: has_many   :events
          belongs_to :team
Event:    belongs_to :calendar

I've a view where 2 forms are displayed:

  1. one for adding a new Calendar, associated to a Team
  2. one for adding a new Event, associated to a Calendar

In my controller, I set up variables with something like:

@team      = Team.find(params[:id])
@calendars = @team.calendars
@calendar  = @team.calendars.build

But in my view, @calendar is called before @calendars

<%= render partial: 'calendars/form', locals: { calendar:  @calendar,  ... } %>
<%= render partial: 'events/form',    locals: { calendars: @calendars, ... } %>

Thus in the events/form partial, the <select> tag contains a line for each calendar, plus one for the newly built calendar (which is empty, baah, ugly).


QUESTION: How could I set (eager load ?) the @calendars so it does not contains non-prersisted records ?


A simple solution that does not immediately set the @calendars variable, but at least does not pollute it:

@calendar = Calendar.new(team_id: @team.id)


Solution 1:[1]

You can call load to immediately load the records from the database.

@team      = Team.find(params[:id])
@calendars = @team.calendars.load
@calendar  = @team.calendars.build

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 spickermann