Really racking my brain on this one. I’m relatively new to Rails and trying to do something that I’m sure is not too difficult.
I have a model “Trip” which has many “Days” which has many “Activities”
I am in the show.html.erb view of “Trip” and in this view, I am rendering a partial for a form that should allow me to create a new “Activity” to be associated with a “Day” or edit an existing “Activity” which already belongs to a “Day”
How do I pass to the form_for in the form partial, the local variable of which “Day” I want to create the new “Activity” for. And using that same form partial, how can I retrieve the “Day” that the “Activity” is associated with? Eventually these will be AJAX loaded objects.
I’ve googled for the past several hours and can’t find any examples similar to this. I really appreciate the help.
routes.rb
resources :trips do
resources :days
end
resources :days do
resources :activities
end
show.html.erb for the Trip
<div id="activities_list">
<%= render :partial => "activities" %>
</div>
<div id="activity_form">
<%= render :partial => "/activities/form", :locals => { :activity => @activity} %>
</div>
<div id="bottom">
<%= link_to 'Edit', edit_trip_path(@trip) %> |
<%= link_to 'Back', trips_path %>
</div>
_activities.html.erb partial
<h1><%= @trip.title %></h1>
<% @trip.days.each do |day| %>
<div id="blech_<%= day.id %>">
<b><%= day.summary %></b>
<% day.activities.each do |activity| %>
<li id="activity_<%= activity.id %>"><%= link_to activity.address, edit_day_activity_path(day, activity), :remote => true %></li>
<% end %>
<% end %>
<%= link_to 'New Activity', new_day_activity_path(day), :remote => true %>
</div>
<% end %>
_form.html.erb partial I know that I need to be calling the day_activity_path with (@day,@activity) variables. but I don’t know how to get the @day variable in here
<%= form_for([@activity], :remote => true) do |f| %>
<fieldset>
<%= f.label :title, "Activity" %><br />
<%= f.text_field :title, :rows => 1 %><br />
</fieldset>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
This is what I ended up doing and it works.
In my show.html.erb for my “Trip”.
show.html.erb
link to “Edit’ an Activity. Notice the :remote => true which tells the Rails controller that this will be an AJAX request so to render edit.js.erb
_form.html.erb This form partial is under the Activities View directory (../views/activities/_form.html.erb).
edit.js.erb This is a file under the Activities view directory (../views/activities/edit.js.erb). Says to grab the DOM element with ID of “activity_form” and render the partial “form”
update.js.erb I included this javascript after hitting update on the Edit form to render an updated partial of the Activities List. So that I don’t have to reload the page to see an update.
routes.rb This is how I nest my routes. Only doing it 1 level following best practices.
resources :trips do
resources :days
end
resources :days do
resources :activities
end