我的项目允许一个家庭页面有多个故事。模型包括关系——“家庭有_很多故事”和“故事属于家庭”。在 routes.rb 文件中,我有以下内容:
resources :families do
resources :stories
end
导致故事控制器的以下路由:
family_stories GET /families/:family_id/stories(.:format) {:action=>"index", :controller=>"stories"}
POST /families/:family_id/stories(.:format) {:action=>"create", :controller=>"stories"}
new_family_story GET /families/:family_id/stories/new(.:format) {:action=>"new", :controller=>"stories"}
edit_family_story GET /families/:family_id/stories/:id/edit(.:format) {:action=>"edit", :controller=>"stories"}
family_story GET /families/:family_id/stories/:id(.:format) {:action=>"show", :controller=>"stories"}
PUT /families/:family_id/stories/:id(.:format) {:action=>"update", :controller=>"stories"}
DELETE /families/:family_id/stories/:id(.:format) {:action=>"destroy", :controller=>"stories"}
以下是相关的控制器方法:
def edit
@story = @family.stories.find(params[:id])
end
def destroy
@story = @family.stories.find(params[:id])
@story.destroy
redirect_to family_stories_url, :notice => "Successfully destroyed story."
end
对于 index.html.erb,nifty 脚手架生成的代码没有考虑关系,并且“Show”、“Edit”和“Destroy”的链接不起作用。经过一番研究,我修改了这些链接的代码,如下所示:
<% for story in @stories %>
<tr>
<td><%= story.title %></td>
<td><%= story.body %></td>
<td><%= link_to "Show", [@family, story] %></td>
<td><%= link_to "Edit", edit_family_story_path([@family, story]) %></td>
<td><%= link_to "Destroy", [@family,story], :confirm => 'Are you sure?', :method => :delete %> </td>
</tr>
<% end %>
当用“[@family,story]”替换原来的“story”变量时,“Show”链接可以正常工作。“销毁”和“编辑”链接不适用于类似的替换。
“Destroy”链接不会产生任何错误,但就像“Show”链接一样 - 记录不会被删除,而是会显示(:confirm 对话框从不显示。)“Edit”链接会生成以下错误:
"No route matches {:action=>"edit", :controller=>"stories", :family_id=>\#[Story id: 1, title: "story01 for family01", body: "body01 for story01 for family01", created_at: "2011-04-09 22:55:14", updated_at: "2011-04-09 22:55:14", family_id: 1]}"
[@family,story] 结构适用于“显示”链接。为什么它不适用于“编辑”和“销毁”链接?如何修改它们以使其正常工作?