gvermag
gvermag

Reputation: 379

How to pass foreign key id as parameter while calling create form in rails 4.x

My user interface needs to be such that a student record can be created:

1) by a student if he/she is over 18 years
OR
2) has to be created by parent if the student is <18 years.

In the student form, I have the Date of birth field, which I can use for that isadult validation, but I'm a little confused how to go about the logic above in general.

I am guessing it can be implemented as passing a parent_id parameter value to the http://localhost:3000/student/new form call. When the user indicates that he is an adult, the parent_id parameter value wont be included, otherwise, if the user is already logged in as a parent, then that parent_id would be passed to http://localhost:3000/student/new?parent_id=1 (say).

Im struggling to understand how this is going to be implemented. Need some sample code for implementation. Please Feel free to ask questions.

Upvotes: 2

Views: 422

Answers (1)

MattyB
MattyB

Reputation: 952

As Iceman suggests, you don't need to pass the parent_id as a parameter. In the controller's create, you can do something like

@student = Student.new(params)
@student.parent_id = @current_user.id if @current_user.isadult?

In the Student model you can add a validation that the current user is over 18 or has a parent id

Upvotes: 1

Related Questions