I would like to create a button so that a user can enroll in a course. The enrolling model belongs_to users and courses and should keep track of enrollment.
I have the following code displayed as a button-form on a course page (looks fine):
<% @enroll = current_user.enrollings.build(course_id: @course.id) %>
<%= form_for(@enroll) do |f| %>
<div><%= f.hidden_field :course_id %></div>
<%= f.submit "Enroll", class: "btn btn-large btn-primary" %>
<% end %>
I have a resources route for enrollings, and when the user clicks on the button, the page goes to /enrollings.
This is the code in the enrolling controller:
def create
@course = Course.find(params[:course_id])
current_user.enroll!(@course)
end
When I click on the button, I get the following error message:
ActiveRecord::RecordNotFound in EnrollingsController#create
Couldn’t find Course without an ID
Why isn’t it passing the course_id with the form? How do I setup the controller correctly?
Try this instead: