I had a general question of what is going on when code like this runs:
<%= form_for(current_user.favorite_relationships.find_by_lesson_id(@lesson),
html: {method: :delete},
remote: true) do |f| %>
<div><%= f.hidden_field :lesson_id %></div>
<%= f.submit "Unfavorite", class: "btn btn-large" %>
<% end %>
specifically the very first line of code. i usually see some form of instance variable instead of
current_user.favorite_relationships.find_by_lesson_id
I can assume that this will go into the FavoriteRelationship controller’s destroy action. Is there anything else someone can infer from that form above? Like what will be available or gets passed in the destroy action?
Presumably, the controller has supplied a
Lessonobject to the view through the variable@lesson. Your current user, aUserobject, presumablyhas_many :favorite_relationships, which in turnbelongs_to :lesson, meaning there is a field within thefavorite_relationshipstable calledlesson_id.Rails builds “magic” finder methods for your models for the fields it contains. If a model has a
lesson_idfield, Rails provides afind_by_lesson_idhelper. Rails is smart enough to extract@lesson.idwhen you pass it an actual Lesson object instead of an integer.The net result is that an object of type
FavoriteRelationshipis being passed into theform_forhelper. This is no different than finding the object in the controller and passing it to the view via a (for example)@favorite_relationshipvariable.The only thing available to the controller on the subsequent request to the FavoriteRelationship’s destroy route is the id of the object to destroy. You’ll be able to access it via
params[:id].