Rails 3渲染/部分

时间:2011-04-07 08:13:18

标签: ruby ruby-on-rails-3

我是Rails 3的新手,我已经按照一些教程进行操作,现在我正在尝试使用创建的代码“玩”。我已经按照http://guides.rubyonrails.org/getting_started.html

的教程进行了操作

我正在尝试使用以下代码在主页上为新帖子呈现表单:

<%= render :partial => "posts/form" %>

帖子/ _form.html.erb如下所示:

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

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

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %><br />
    <%= f.text_area :content %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

这是我得到的错误:

 undefined method `model_name' for NilClass:Class
Extracted source (around line #1):

1: <%= form_for(@post) do |f| %>
2:   <% if @post.errors.any? %>
3:     <div id="error_explanation">
4:       <h2><%= pluralize(@post.errors.count, "error") %> prohibited this post from being saved:</h2>
Trace of template inclusion: app/views/home/index.html.erb

Rails.root: d:/server/cazare

Application Trace | Framework Trace | Full Trace
app/views/posts/_form.html.erb:1:in `_app_views_posts__form_html_erb___794893824_70478136_519766'
app/views/home/index.html.erb:5:in `_app_views_home_index_html_erb__967672939_70487520_0'

我知道这对你们中的一些人来说似乎是件小事,但我正在努力了解Rails上的一切是如何运作的,所以我希望你能理解我。

提前致谢!

3 个答案:

答案 0 :(得分:5)

@post变量未在Controller中实例化:)

所以控制器动作中的"@post = Post.new"应该可以解决问题

答案 1 :(得分:1)

Rails正在尝试为对象@post构建表单。为了做到这一点,它需要知道什么类型的对象@post;这样,它可以找到对象中的任何现有数据并将其填入表单中。 Rails将一个方法移植到名为model_name的对象上进行查找,但不会将其移植到NilClassnil对象的类)上。

我怀疑你没有在任何地方定义@post - 它是Controller的一个实例变量,所以你希望控制器从数据库中找到@post,或者调用{{ 1}} - 所以它是@post = Post.new

答案 2 :(得分:0)

在帖子/ _form.html.erb中,

变化

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

<%= form_for(Post.new) do |f| %>
相关问题