0

I'm new to Ruby on Rails. I've seen that in a resources_controller file in whenever you call resources#new it lands me to new.html.haml file which contains a form. When I click on Submit button it redirects to me the the create function of the above resources_controller.rb file. Can anyone explain me how? Actually I want to do something like this:

I want to create a new student only if the student with a given roll number doesn't exist. For that new.html.haml contains a form where there is only one field for roll number, if the student with that roll number does not exist then a new haml should be called where there will be another form where one will enter the student details and only after submission of this latter form create should be called. And when the student already exits the form fields should be filled automatically.

I cannot figure out how to do this, because whenever I click the submit button in the form in new.html.haml it is redirecting me always to create.

Alex Shesterov
  • 26,085
  • 12
  • 82
  • 103
Joy
  • 4,197
  • 14
  • 61
  • 131

1 Answers1

0

you could simply add some code in top of resources#create function to check if the number corresponds to an existing record or not.

In case it corresponds to an existing one, you redirect the user to the corresponding edit page (that would look like /resources/:id/edit) so that he can fill the extended form.

In case it's a new record, you continue with the regular treatment.

So, you will have to add a code that looks like this

resources_controller.rb

def create
  if !(resource = Resource.find(params[:id])).blank?
    redirect_to edit_resource_url(resource)
  end
  ...
amine
  • 502
  • 5
  • 14
  • Your answer is partially correct, because when the resource does not exist, I need to redirect to another form where user will enter the resource details info and then submission of that form will redirect the user back to create function of controller. I don't understand how submission of the latter form will redirect the user to create. – Joy Sep 08 '13 at 10:38
  • if the resource exists you could redirect to a view that has a different form that you can build yourself and in the line form_for, set the attribute like that: :controller => 'resources', :action => 'your_custom_action' then you need to define your function in the controller 'def your_custom_action ...' and maybe in the routes you will have to add a new route to this function – amine Sep 08 '13 at 10:56