我对Rails和这个Q& A网站都很陌生!大家好,我是法国Rails测试员。我已经将此问题交叉发布到Railsforum,以便有更好的机会获得答案:)(http://railsforum.com/viewtopic.php?id=44238)
我需要帮助。看起来很简单,但在我看来,没有详细记录(我在网上浏览了3天没有找到一个干净的答案。这里有一些部分解决方案,但对于新手来说不是一个完整而干净的解决方案!)
我想在默认的脚手架控制器中添加一些操作,以便以相同的形式处理多个记录的创建和修改。
rails generate scaffold Item title:string
这是示例脚手架代码:
class ItemsController < ApplicationController
# GET /items
# GET /items.xml
def index
@items = Item.all
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @items }
end
end
# GET /items/1
# GET /items/1.xml
def show
@item = Item.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => @item }
end
end
# GET /items/new
# GET /items/new.xml
def new
@item = Item.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => @item }
end
end
# GET /items/1/edit
def edit
@item = Item.find(params[:id])
end
# POST /items
# POST /items.xml
def create
@item = Item.new(params[:item])
respond_to do |format|
if @item.save
format.html { redirect_to(@item, :notice => 'Item was successfully created.') }
format.xml { render :xml => @item, :status => :created, :location => @item }
else
format.html { render :action => "new" }
format.xml { render :xml => @item.errors, :status => :unprocessable_entity }
end
end
end
# PUT /items/1
# PUT /items/1.xml
def update
@item = Item.find(params[:id])
respond_to do |format|
if @item.update_attributes(params[:item])
format.html { redirect_to(@item, :notice => 'Item was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => @item.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /items/1
# DELETE /items/1.xml
def destroy
@item = Item.find(params[:id])
@item.destroy
respond_to do |format|
format.html { redirect_to(items_url) }
format.xml { head :ok }
end
end
end
<h1>New item</h1>
<%= render 'form' %>
<%= link_to 'Back', items_path %>
<h1>Editing item</h1>
<%= render 'form' %>
<%= link_to 'Show', @item %> |
<%= link_to 'Back', items_path %>
<%= form_for(@item) do |f| %>
<% if @item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@item.errors.count, "error") %> prohibited this item from being saved:</h2>
<ul>
<% @item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :title %><br />
<%= f.text_field :title %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
在我看来,我需要在Item控件中添加4个方法:
然后,我需要创建2个新视图:
有人想帮我写下这4个动作和2个视图吗?我真的很感激。
谢谢! :)
注意:在我的应用程序项目中是parentItems的子项,但我不想使用nested_form在parentItems表单中创建项目,如在railscast 196和197中。