Reputation: 3281
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?
Upvotes: 0
Views: 104
Reputation: 4796
remote: true
)The @favorites = current_user.favorite_relationships.find_by_lesson_id(@lesson)
, IMO, should be placed inside the controller rather than the view and the view should have @favourites
in the form_for
part. That is the reason for the observation you've made about instance variables
Upvotes: 1
Reputation: 239541
Presumably, the controller has supplied a Lesson
object to the view through the variable @lesson
. Your current user, a User
object, presumably has_many :favorite_relationships
, which in turn belongs_to :lesson
, meaning there is a field within the favorite_relationships
table called lesson_id
.
Rails builds "magic" finder methods for your models for the fields it contains. If a model has a lesson_id
field, Rails provides a find_by_lesson_id
helper. Rails is smart enough to extract @lesson.id
when you pass it an actual Lesson object instead of an integer.
The net result is that an object of type FavoriteRelationship
is being passed into the form_for
helper. This is no different than finding the object in the controller and passing it to the view via a (for example) @favorite_relationship
variable.
what will be available or gets passed in the destroy action?
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]
.
Upvotes: 1