我正在製作一個網頁,其中有一個用戶可以註冊以贏得iPad的頁面。我創建了一個模型ipad.rb
和一個ipads_controller.rb
,並且在遷移中有三列用於名稱,電子郵件和推特處理。當Rails沒有自動創建路由時,我感到很驚訝(我認爲它應該始終這樣做)。Rails:`ipads_path'與iPad.rb模型和ipads_session控制器的錯誤消息
我的路線添加文件
resource :ipad
match '/signup', :to => 'ipads#new'
當我試圖創建註冊表單,我完全完成它
undefined method `ipads_path' for #<#<Class:0x00000103a64ec0>:0x00000103a49aa8>
這讓我感到驚訝,因爲爲什麼是之前得到這個錯誤消息它是複數?
到目前爲止,我只創建了一個new.html.erb
形式和模型ipad.rb
並在ipads_controller.rb
new
和create
兩個動作。
任何人都可以看到我做錯了什麼?即爲什麼Rails認爲我需要一種方法ipads_path
。另外請注意,我創建了一個模型IPad.rb,但刪除了它和遷移。
new.html.erb
<h1>Win an iPad</h1>
<h1>Sign up for iPad</h1>
<%= form_for(@ipad) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :email %><br />
<%= f.text_field :email %>
</div>
<div class="actions">
<%= f.submit "Sign up" %>
</div>
<% end %>
ipad.rb
class Ipad < ActiveRecord::Base
attr_accessible :name, :email, :twitter
email_regex = /\A[\w+\-.][email protected][a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => { :maximum => 50 }
validates :email, :presence => true,
:format => { :with => email_regex },
:uniqueness => true
end
ipads_controller.rb
class IpadsController < ApplicationController
def new
@ipad = Ipad.new
@title = "iPad Contest"
end
def create
@ipad = Ipad.new(params[:ipad])
if @ipad.save
# Handle a successful save.
else
@title = "iPad Contest"
render 'new'
end
end
end
的routes.rb
Enki::Application.routes.draw do
namespace 'admin' do
resource :session
resources :posts, :pages do
post 'preview', :on => :collection
end
resources :comments
resources :undo_items do
post 'undo', :on => :member
end
match 'health(/:action)' => 'health', :action => 'index', :as => :health
root :to => 'dashboard#show'
end
resources :archives, :only => [:index]
resources :pages, :only => [:show]
resource :ipad
match '/signup', :to => 'ipads#new'
constraints :year => /\d{4}/, :month => /\d{2}/, :day => /\d{2}/ do
get ':year/:month/:day/:slug/comments' => 'comments#index'
post ':year/:month/:day/:slug/comments' => 'comments#create'
get ':year/:month/:day/:slug/comments/new' => 'comments#new'
get ':year/:month/:day/:slug' => 'posts#show'
end
scope :to => 'posts#index' do
get 'posts.:format', :as => :formatted_posts
get '(:tag)', :as => :posts
end
root :to => 'posts#index'
end
我覺得你的模型的選擇很可能得到改善。儘管你所做的並不是「錯誤的」,但確切地說,它不是特別明確的代碼,也不可能是非常可重用的。我會考慮對它進行重構,以便您擁有一個與它關聯的Entry模型的Contest模型。看起來很奇怪,有一個名爲IPad的模型映射到用戶信息表。 – 2012-01-09 01:33:58
我同意。我是小白。這可能是我第二次創建了一個模型(除了一本書以外)。 – Leahcim 2012-01-09 01:39:24