DNorthrup
DNorthrup

Reputation: 847

Rails Route Issue - Plural or Singular?

I'm unsure what to post here script wise. I'm trying to complete a tutorial and it wants me to create Advertisement. I made the Controller/Model, but I'm having a couple issues.

My index is showing all of the ads, but when I try to create one, I get an error

undefined method `advertisements_path' for #<#:0x007fa84c5a59f0>

Now I see it mentions 'advertisementS' so I know it wants plural. My controller is singular. If I go into routes and I add resources :advertisements AS WELL, it -will- allow me to create an Ad, but when it goes to submit it, I get errors (Likely since everything is still set to AdvertisementController (Singular).

I'm not quite sure what code to post, so I'll post things I think are relevant.

Rails.application.routes.draw do
  resources :posts
  resources :advertisement

This is where I can add a plural resources to get it to 'load' but fail to save.

<%= form_for @advertisement do |f| %>
  <div class="form-group">
      <%= f.label :title %>
      <%= f.text_field :title, class: 'form-control', placeholder: "Enter post title" %>
  <div class="form-group">
    <%= f.submit "Save", class: 'btn btn-success' %>
  </div>

THIS is where I am getting my initial warning, on the "form_for @advertisement" line.

  def create
@advertisement = Advertisement.new
@advertisement.title = params[:advertisement][:title]
@advertisement.copy = params[:advertisement][:copy]
@advertisement.price = params[:advertisement][:price]
if @advertisement.save
  flash[:notice] = "The Ad was saved."
  redirect_to @advertisement
else
  flash[:error] = "There was an error saving the ad. Please try again."
  render :new
end

end

This references my def create from AdvertisementController.

(Essentially the purpose of the tutorial is to duplicate almost exactly what we do for Posts. It worked, up until now. Functionality works until I go to create a new one.

I've been working on it for a couple hours, but I'm struggling to understand when to use plural vs singular. (There is no integration as of yet, so belong_to isn't relevant yet.

Upvotes: 1

Views: 247

Answers (2)

DNorthrup
DNorthrup

Reputation: 847

map.resources :dogs # => blows up map.resources :dog # is ok, but... dogs_path # => blows up dog_path # => ok

Based upon input I found in another thread, this made me realize I would need a plural controller.

Re-creating the controller as plural (advertisementS) resolved issue.

Upvotes: 1

wiesion
wiesion

Reputation: 2435

The rails convention of naming Controllers is plural. It's possible to use singular, but it gets you into problems like you are having now. So, rename your Controller to plural version and it should be fine.

Also

resources :posts 
resources :advertisement

is not consistent, i would suggest that you keep your route names plural as well.

Upvotes: 1

Related Questions