动图效果图
实际运行代码
* config/routes.rb *
resources :books do
collection do
+ post 'book_update'
end
end
app/controllers/books_controller.rb
* def destroy
def book_update
@book = Book.find(params[:id]) #接受view层传递的id参数
if @book.book_state == "上架" #图书状态如果为"上架"字符串
@book.update(book_state: "下架") #更新为"下架"字符串状态
flash[:error] = "下架成功"
else #图书状态为非"上架"字符串
@book.update(book_state: "上架") #更新为"上架"字符串状态
flash[:error] = "上架成功"
end
redirect_to :back
end
app/views/books/index.html.erb
<% @books.each do |book| %>
<tr class="text-info">
<td><%= book.title %></td>
<td><%= book.text %></td>
<td>
#线上图书状态字符串 #动作路由 #设定传递id值 #路由执行post动作
+ <%= link_to("#{book.book_state}", book_update_books_path(:id => book.id), method: :post , :class => "btn btn-xs btn-default") %>
</td>