简体   繁体   中英

Partial View Ruby on Rails

I have 3 models:

  • customer
  • book_manager
  • book

The customer can edit its own setting, like a profile account. However, it renders different models, such has book . To do this I decided to render the file book/form has follow <% render book/form %> .

When the profile page loads up, the customer may view in the book sections either nothing if nothing has been written before, or something if he already wrote something before. In the customer controller page I have the following code to fetch the information:

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

In the books/_form.html.erb I have then the following:

<%= 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 %>

In book controller edit , I have nothing or where should I place my command @book so they can speak?

I have the following error:

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>
<% render book/form.html.erb %>

应该

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

You have at least one simple error in your code

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

This will indeed return the most recent book, but it will return it in an array.

Instead of calling limit(1) you should use the method first

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM