部分视图Ruby on Rails

时间:2012-07-31 14:40:13

标签: ruby-on-rails ruby ruby-on-rails-3

我有3个型号:

  • 客户
  • book_manager

customer可以编辑自己的设置,例如个人资料帐户。但是,它会呈现不同的模型,例如book。为此,我决定渲染文件book/form已跟随<% render book/form %>

当个人资料页面加载时,如果以前没有写过任何内容,客户可以在书中查看任何内容,或者如果他之前已经写过某些内容的话。在客户控制器页面中,我有以下代码来获取信息:

def edit
  @book = current_customer.books.order("created_at DESC").limit(1)
end

books/_form.html.erb我有以下内容:

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

      <ul>
      <% @book.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
  <div class="field">
    <%= f.label :description %><br />
    <%= f.text_field :description %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

book控制器edit中,我什么都没有,或者我应该在哪里发出命令@book以便他们可以发言?

我有以下错误:

NoMethodError in Customers#edit

Showing /home/jean/rail/map/app/views/books/_form.html.erb where line #1 raised:

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

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

2 个答案:

答案 0 :(得分:1)

<% render book/form.html.erb %>

应该是

<%= render '/books/form' %>

答案 1 :(得分:0)

您的代码中至少有一个简单错误

@book = current_user.books.order("created_at DESC").limit(1)

这确实会返回最新的书,但它会以数组的形式返回。

您应该使用方法limit(1)

,而不是调用first
@book = current_user.books.order("created_at DESC").first