0

I've got a User model and an Account controller. When a user visits the /account url, it should show a form containing a text field with the username in it and a button to submit the form.

I have match '/account' => 'account#index' in my routes.

In my controller I have this method defined:

def index
  @user = User.find(session[:user_id])
end

(Checking the user authentication happens in a before_filter)

Now the form shows correctly and is even populated correctly. However, I need to know how to tell whether the form has been submitted. What is the rails way? Do I have a separate route that watches for a POST request to /account? Or do I detect the request type in the index method? At what point do I decide whether the form has been submitted or not?

Matthew
  • 15,282
  • 27
  • 88
  • 123

1 Answers1

1

You could detect if the form has been submitted inside of the index controller. I believe the params hash gets sets the key :method to the method used for the request.

An alternative is to redo the way you route. Instead of match '/account' => 'account#index' you can do:

get '/account' => 'account#index'
post '/account' => 'account#post_action'

And then inside your controller you could do:

def index
  @user = User.find session[user_id]
end

def post_action
  @user = User.find session[user_id]
  if @user.update_attributes params[:user]
    flash[:notice] = 'Update Successful'
    render :action => index
  else
    flash[:notice] = 'Update Unsuccessful'
    render :action => index
  end
end
Max
  • 15,157
  • 17
  • 82
  • 127