2014-04-04 103 views
0

我试图在我的页面索引视图中添加一个预启动注册电子邮件表单。我根据自己的观点制作了一个表格,然后创建了一个控制器,然后创建了模型和表格并运行迁移。这是做到这一点的正确方法吗?从未定义的方法premails_path为#<#<Class:0x4fa8530>:0x52c1ec8>

<%= form_for(@premail) do |f| %> 
    <% if @premail.errors.any? %> 
     <div id="error_explanation"> 
     <h2><%= pluralize(@premail.errors.count, "error") %> prohibited this link from being saved:</h2> 

我的页面控制器

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

有以下:

我收到以下错误:

NoMethodError in Pages#index 
undefined method `premails_path' for #<#<Class:0x4fa8530>:0x52c1ec8> 

上线

class PagesController < ApplicationController 

    def index 
     @premail = Premail.new 
    end 




end 

我的网页索引视图有以下几点:

<%= form_for(@premail) do |f| %> 
    <% if @premail.errors.any? %> 
    <div id="error_explanation"> 
     <h2><%= pluralize(@premail.errors.count, "error") %> prohibited this link from being saved:</h2> 

     <ul> 
     <% @premail.errors.full_messages.each do |msg| %> 
     <li><%= msg %></li> 
     <% end %> 
     </ul> 
    </div> 
    <% end %> 

    <div class="field"> 
    <%= f.label :Email %><br /> 
    <%= f.text_field :Email %> 
    </div> 
    <div class="actions"> 
    <%= f.submit %> 
    </div> 
<% end %> 

我生成以下模型:

class Premail < ActiveRecord::Base 


end 

和下面的数据库迁移表:

class CreatePremails < ActiveRecord::Migration 
    def change 
    create_table :premails do |t| 

     t.text :email 

     t.timestamps 
    end 
    end 
end 

我能做些什么不同做这个工作?

+2

您可以发布您的路线吗? – Pavan

+0

尝试运行'耙路线'并检查正确的路线 – LHH

+1

是的,听起来像你已经忽略了在你的'config/routes.rb'文件中添加premails条目 –

回答

0

因为你装上Pages#index这种形式,您将受益于使用url: argument这样的:

<%= form_for @premail, url: pages_index_path do |f| %> 

更新

Rails guide

Resource-oriented style

In the examples just shown, although not indicated explicitly, we still need to use the :url option in order to specify where the form is going to be sent. However, further simplification is possible if the record passed to form_for is a resource, i.e. it corresponds to a set of RESTful routes, e.g. defined using the resources method in config/routes.rb. In this case Rails will simply infer the appropriate URL from the record itself. For example,

<%= form_for @post do |f| %> ... <% end %> is then equivalent to 

something like:

<%= form_for @post, as: :post, url: post_path(@post), method: :patch, 
html: { class: "edit_post", id: "edit_post_45" } do |f| %> ... <% 
end %> 

当您使用@premails instance var(它是Premail类的一个实例)时,您的form_for帮助程序将尝试使用premails路径。要使用pages路径(根据您的问题),您需要手动设置url选项

+0

为什么?不明白原因.. – user3408293

+0

让我为你更新答案 –

+0

因此,我可以明确说明URL并使用其中一个页面根目录,而不必为premail添加一个资源?这是什么?如果那是不正确的,我是新来的编码原谅我的无知。 – user3408293

相关问题