0
我在books.index視圖中列出了所有「書籍」。我希望能夠在相同的視圖中編輯它們。當我點擊其中一本書時,是否有辦法呈現編輯表單?Rails,點擊編輯窗體
截至目前,我正在爲每本書打印出部分內容,並且爲每本書添加了單獨的表單。但是,我必須隱藏所有這些內容,並在每次有人點擊一本書時追加它們。
我在想,應該有某種方式讓我每次有人點擊它時呈現相同的表單,並給它一個書的ID,然後它會希望填充正確的信息。
希望這是有道理的。 謝謝!
控制器書:
class BooksController < ApplicationController
def index
@Books = Book.all
@book = Book.new
end
def show
@book = Book.find(params[:id])
@chapter = chapter.new
end
def new
@book = Book.new
if !current_user.admin?
redirect_to @book
end
end
def edit
@book = Book.find(params[:id])
if !current_user.admin?
redirect_to @book
end
end
def create
@books = Book.all
@book = Book.new(book_params)
if @book.save
respond_to do |format|
format.js
format.html { render action: "index", notice: 'Book was successfully created.' }
format.json { render json: @book, status: :created, location: @book }
end
else
respond_to do |format|
format.js
format.json { render json: @book.errors, status: :unprocessable_entity }
format.html { render action: "index", notice: 'feil' }
end
end
end
def update
@book = Book.find(params[:id])
if @book.update(book_params)
redirect_to @book
else
render 'edit'
end
end
def destroy
@book = Book.find(params[:id])
@book.destroy
redirect_to books_path
end
private
def book_params
params.require(:book).permit(:title, :pages)
end
end
查看,books.index
<div id="wrapper">
<section id="page_wrap">
<h1>books</h1>
<table id="all_exps">
<tr>
<th>Title</th>
<th>abbr</th>
<th>pages</th>
<th>chapter</th>
<th class="edits"></th>
<%unless !session[:user_id]%>
<% if current_user.admin? %>
<th class="edits"></th>
<th class="edits"></th>
<% end%>
<%end%>
</tr>
<% @books.each do |book| %>
<%= render 'book', book: book %>
<% end %>
</table>
<%unless !session[:user_id]%>
<% if current_user.admin? %>
<div class="makenew">
<a href="" class="add_new"> Add Book</a>
</div>
<div id="somedialog" class="dialog">
<div class="dialog__overlay"></div>
<div class="dialog__content">
<div class="close"><%= image_tag('icons/delete2.png') %></div>
<h2>Add Book</h2>
<%= render 'form' %>
</div>
</div>
<% end%>
<% end%>
</section>
</div>
查看部分_book
<tr>
<td><%= book.title %></td>
<td><%= book.abbr %></td>
<td>
</td>
<td><%= book.chapters.length %></td>
<td class="edits show"><%= link_to image_tag('icons/eye.png'), book_path(book) %></td>
<%unless !session[:user_id]%>
<% if current_user.admin? %>
<td class="edits"><%= link_to image_tag('icons/edit3.png'), edit_book_path(book) %></td>
<td class="edits"><%= link_to image_tag('icons/delete2.png'), book_path(book),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end%>
<%end%>
</tr>
<%= form_for book do |f| %>
<%= f.label :title %>
<%= f.text_field :title %>
<%= f.label :pages %>
<%= f.text_field :pages %>
<%= f.submit %>
<% end %>
Book模型
class Book < ActiveRecord::Base
has_many :chapters, dependent: :destroy
validates :title, presence: true,
length: { minimum: 3 }
end
請顯示您的代碼以使其更清晰。控制器,模型和視圖將會很有用。 –
你必須發佈一些代碼,以便我們可以看到你迄今爲止做了什麼。 – Emu
開始閱讀關於Ajax –