Reputation: 688
Scenario: a user (class: User
) wants to apply to a course (class: Course
) online, by creating an application (class Application
).
They visit an application page, at /applications/:id
where id is the course id. This is the controller:
def new
@course = Course.find_by_id(params[:id])
@application = Application.new
end
def create
@application = Application.new(application_params)
@course = Course.find_by_id(params[:id])
@application.course_id = @course.id
@application.save
end
This line fails
@course = Course.find_by_id(params[:id])
because in the method that handles the POST request you can't access the parameters, but I require them to set the course_id on the application.
Upvotes: 0
Views: 140
Reputation: 6321
If your Routes nested and associated, You can use ActiveRecord method since rails can done for less code.
def create
@course = Course.find(params[:id]) #if its nested and associated then (params[:course_id])
@application = @course.applications.new(application_params)
@application.save
end
Upvotes: 1
Reputation: 701
A new_whatever_path link will only pass an id if the resource is nested. So I think you're routes should look something like:
resources :course do
resources :application, only: [:new, :create]
end
And then you can do a link_to "Apply:, new_course_application_path(@course), etc.
Upvotes: 2