简体   繁体   中英

Rails NoMethodError

I'm having an issue very similar to the one asked in this question here: NoMethodError / undefined method `foobar_path' when using form_for However the answer there confuses me.
I went through Michael Hartel's Ruby on Rails tutorial before developing the application I'm working on at the moment, I tried to copy exactly what he did when he created a user model as I created my model. My application is designed to be a database for university professors, so the model I'm using is called "professor" but it's the same concept as "user".

Here is the code for my New.html.erb where is where users go to create a new professor:

<%provide(:title, 'Add a professor') %>
<div class="jumbotron">
<h2> New Professor</h2>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_for (@professor) do |f| %>
    <%= f.label "First Name" %>
    <%= f.text_field :fname %>

    <%= f.label  "Last Name" %>
    <%= f.text_field :lname %>

    <%= f.label "School" %>
    <%= f.text_field :school %>

    <%= f.submit "Add this professor", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>
</div>

And then here is the code from the Professor_controller.rb

class ProfessorController < ApplicationController
  def show
    @professor = Professor.find(params[:id])
  end

  def new
    @professor = Professor.new
  end
end

When I replace

  <%= form_for (@professor) do |f| %>  

In new.html.erb with:

  <%= form_for (:professor) do |f| %>

It works. The thread I mentioned above said something about adding a route for the controller. My routes.rb looks like this:

Rails.application.routes.draw do

root 'static_pages#home'
get  'about' => 'static_pages#about'
get 'newprof' => 'professor#new'
resources :professor

And I don't believe that in Michael Hartel's book he does anything differently. I'm still very new to Rails so forgive me if this is a bit of an easy question, I've been stuck on it for a few days and I've tried numerous work arounds, using the instance of :professor works but @professor does not and I don't know why.

Within the Rails environment it's very important to be aware of the pluralization requirements of various names. Be sure to declare your resources as plural:

resources :professors

Declaring it in the singular may mess up the automatically generated routes, you'll get thing like professor_path instead of professors_path . You can check what these are with:

rake routes

If you get errors about x_path being missing, check that there's a route with the name x in your routes listing. The most common case is it's mislabeled, a typo, or you've failed to pluralize it properly.

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