我是 ruby on rails 的新手,我刚刚创建了一个小项目,用于添加、更新和删除 mysql db 中的记录
我能够成功地从 ruby 应用程序的 mysql db 添加和删除记录
但问题只是当我尝试更新现有记录时
我的代码如下,
控制器:
class BookController < ApplicationController
def list
@books = Book.find(:all)
end
def show
@book = Book.find(params[:id])
end
def new
@book = Book.new
@subjects = Subject.find(:all)
end
def create
@book = Book.new(params[:book])
if @book.save
redirect_to :action => 'list'
else
@subjects = Subject.find(:all)
render :action => 'new'
end
end
def edit
@book = Book.find(:all)
@subjects = Subject.find(:all)
end
def update
@book = Book.find(params[:id])
if @book.update_attributes(params[:book])
redirect_to :action => 'show', :id => @book
else
@subjects = Subject.find(:all)
render :action => 'edit'
end
end
def delete
Book.find(params[:id]).destroy
redirect_to :action => 'list'
end
def show_subjects
@subject = Subject.find(params[:id])
end
end
列表 HTML:
<% if @books.blank? %>
<p>There are not any books currently in the system.</p>
<% else %>
<p>These are the current books in our system</p>
<ul id="books">
<% @books.each do |c| %>
<li>
<%= link_to c.title, {:action => 'show', :id => c.id} -%>
<b><%= link_to "edit", {:action => 'edit', :id => c.id} %></b>
<b> <%= link_to "Delete", {:action => 'delete', :id => c.id},
:confirm => "Are you sure you want to delete this item?" %></b>
</li>
<% end %>
</ul>
<% end %>
<p><%= link_to "Add new Book", {:action => 'new' }%></p>
Edit HTML:
=========
<h1>Edit Book Detail</h1>
<%= form_tag(:action=> "update") do%>
<p><label for="book_title">Title</label>:
<%= text_field 'book', 'title' %></p>
<p><label for="book_price">Price</label>:
<%= text_field 'book', 'price' %></p>
<p><label for="book_subject">Subject</label>:
<%= collection_select(:book, :subject_id,
@subjects, :id, :name) %></p>
<p><label for="book_description">Description</label><br/>
<%= text_area 'book', 'description' %></p>
<%= submit_tag "Save changes" %>
<%end %>
<%= link_to 'Back', {:action => 'list' } %>
当我尝试从 URL 编辑记录时,出现以下异常http://localhost:3000/book/edit/5
,
Showing C:/app/app/views/book/edit.html where line #5 raised:
undefined method `title' for #<Array:0x33315c0>
Extracted source (around line #5):
2: <%= form_tag(:action=> "update") do%>
3:
4: <p><label for="book_title">Title</label>:
5: <%= text_field 'book', 'title' %></p>
6: <p><label for="book_price">Price</label>:
7: <%= text_field 'book', 'price' %></p>
8: <p><label for="book_subject">Subject</label>:
顺便说一句,我正在使用 rails3、ruby1.2 和 mysql5.5。
由于我处于学习曲线中,如果有人可以在这个问题上帮助我,那将非常有用。