简体   繁体   中英

Rails Form_for with Model No Controller

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>&nbsp;</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"):

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM