I am working on a very simple project to learn Rails better, coming from a C# background. It seems to be rendering the incorrect form action with my code.
It currently has 2 models which are using the routes of
resources :leaks
resources :passwords
This is to give me the basic routes:
Matts-MacBook-Pro:pwcrack-webgui mandreko$ rvm 1.9.3 do rake routes
leaks GET /leaks(.:format) leaks#index
POST /leaks(.:format) leaks#create
new_leak GET /leaks/new(.:format) leaks#new
edit_leak GET /leaks/:id/edit(.:format) leaks#edit
leak GET /leaks/:id(.:format) leaks#show
PUT /leaks/:id(.:format) leaks#update
DELETE /leaks/:id(.:format) leaks#destroy
passwords GET /passwords(.:format) passwords#index
POST /passwords(.:format) passwords#create
new_password GET /passwords/new(.:format) passwords#new
edit_password GET /passwords/:id/edit(.:format) passwords#edit
password GET /passwords/:id(.:format) passwords#show
PUT /passwords/:id(.:format) passwords#update
DELETE /passwords/:id(.:format) passwords#destroy
In my leakscontroller.rb, I have 2 methods, to try create a new leak:
def new
@leak = Leak.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @leak }
end
end
def create
@leak = Leak.new(params[:leak])
if @leak.save
redirect_to @leak, :notice => "Successfully created leak."
else
render :action => 'new'
end
end
And lastly, in my new.html.erb, I have:
<%= form_for @leak, :url => { :action => "create" } do |f| %>
<div class="field>
<%= f.label :source %>
<%= f.text_field :source %>
</div>
<div class="field">
<%= f.label :file %>
<%= f.file_field :file %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>
I would think that with this view, it would create a form with action=Create, but the following code is generated:
<form accept-charset="UTF-8" action="/leaks" class="new_leak" enctype="multipart/form-data" id="new_leak" method="post">
Any clue why this would be the case?
Because of Rails’ restful nature and some serious metaprogramming, the
form_forhelper when using with an instance ofActiveRecordobject, assumes that a simple:When submitted would make a
POSTto thecreateaction on your controller.If you need a more specific form, that do not goes according to the default patterns a Rails App follows, you can use a
form_taghelper.For example if you have a
secret_actionin your controller, you create a route in yourroutes.rb.And a form like this:
And you get the behavior you expect. Once you understand the basic of routing, paths, forms in Rails, you would do these things without even thinking.
Try reading some of this: http://guides.rubyonrails.org/routing.html