Reputation: 27
I'm a new user of Ruby on Rails, and I'm getting confused when I attempt to add data to a model without using an associated controller. I have a controller, admins_controller, which has the administrative ability to add a body (with a name and color field) to the body table, performed on the "committees" view. I've set up a form_for on the committees view but can't seem to configure my routes to correctly add the body to the database.
Routes file:
get 'admin' => 'admins#home'
get 'admin/committees' => 'admins#committees'
get 'admins/newbody' => 'admins#new_body'
resources :admins do
collection do
get :newbody
post :committees
end
end
Committees View:
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_for(@body, :url => {:controller => "admins", :action => "newbody"}) do |f| %>
<%= f.label :type %>
<%= f.select :name, ['Red', 'Blue', 'Green', 'White', 'Special Programs']%>
<%= f.label :name %>
<%= f.select :name, ['Senate', 'House', 'Executive', 'Executive',
'Supreme Court']%>
<p> </p>
<div class="col-md-12">
<%= f.submit "Create body", class: "btn btn-primary" %>
</div>
<% end %>
</div>
</div>
Admin Controller:
def committees
@body = Body.new
end
def newbody
@body = Body.new(body_params)
redirect_to committees
end
Body model: class Body < ActiveRecord::Base
validates :name, presence: true, format: {with: /\b[A-Z].*?\b/}
validates :color, format: {with: /Red|White|Green|Blue|Special Programs/}
end
The error I get is:
ActionController::RoutingError (No route matches [POST] "/admins/newbody"):
Upvotes: 1
Views: 459
Reputation: 1502
You are getting this error because your routes file does not define a POST
method for admins/newbody. It looks like your routes.rb file should be formatted like this:
get 'admin' => 'admins#home'
resources :admins do
collection do
post 'newbody'
get 'committees'
end
end
This has some changes worth noting. Firstly, this removes the route of GET
'admins/newbody'; since you're creating a resource at that route, you shouldn't be using a GET
anyway. It also changes the route 'admin/committees' to 'admins/committees', which follows the expected Rails naming conventions more closely.
In the AdminsController#newbody, you should probably also use @body = Body.create(body_params)
because create will save the newly made record to the database.
Upvotes: 0