Hi,
I have a simple form in my controller “before_home”. In the form I want
to create a user, si I use the users_path on my form.
But look at the html generated… Why do I have an action before_home? I
should be “users” in the action.
Does someone knows where this could come from?
form_for expects the first parameter to be a new user object and if
that isn’t supplied then the form action is set to the action that
rendered the page; this is why you see action="/before_home". The
reason user_path isn’t working is because it doesn’t reference a user
object. If you wish to have the form submitted to /user then set up
the user object and specify the url. See below…
To create a user I suggest you create a new user object and store it
in an instance variable:
@user = User.new
Then in the form_for method you can use that value:
Thanks for your help Floyd, it works now.
However, I have another issue. How do I display the errors regarding
that my form is in a different controller.
if @user.save
flash[:notice] = "Successfully created user."
redirect_to root_path
else
render :action => 'index', :controller => "before_home"
end
form_for expects the first parameter to be a new user object and if
that isn’t supplied then the form action is set to the action that
rendered the page; this is why you see action="/before_home". The
reason user_path isn’t working is because it doesn’t reference a user
object. If you wish to have the form submitted to /user then set up
the user object and specify the url. See below…
To create a user I suggest you create a new user object and store it
in an instance variable:
@user = User.new
Then in the form_for method you can use that value:
In response to your second question, you would not be able to
redisplay the form with errors by using render because the action is
in another controller. However you can render the template that
created the form:
if @user.save
flash[:notice] = “Successfully created user.”
redirect_to root_path
else
render :template => “before_home/new” # I am assuming new was the
action in before_home
end
This will redisplay the form along with the errors.
However, you should consider your application design, it would be
easier to control the creating and updating of records under the
controller that is related to a specific model. Consider implementing
a more RESTful application, contact for more info or if you have
further problems.
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.