How to access params in post request

2019-09-12 04:40发布

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.

2条回答
Luminary・发光体
2楼-- · 2019-09-12 04:54

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.

查看更多
何必那么认真
3楼-- · 2019-09-12 05:04

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
查看更多
登录 后发表回答