私のプロジェクトでは、ファミリー ページに複数のストーリーを含めることができます。モデルには、「Family has_many stories」および「Story belongs to family」という関係が含まれます。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 の場合、気の利いたスキャフォールディングによって生成されたコードは関係を考慮せず、「表示」、「編集」、および「破棄」のリンクは機能しません。いくつかの調査の後、これらのリンクのコードを次のように変更しました。
<% 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 %>
元の「story」変数を「[@family, story]」に置き換えると、「Show」リンクが正常に機能します。「破棄」および「編集」リンクは、同様の置換では機能しません。
「破棄」リンクはエラーを発生させませんが、「表示」リンクと同じように機能します。レコードは削除されず、代わりに表示されます (:confirm ダイアログは表示されません)。「編集」リンクは次のエラーを生成します。
"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] コンストラクトは、「表示」リンクに適しています。「編集」リンクと「破棄」リンクが機能しないのはなぜですか? 正しく動作するように変更するにはどうすればよいですか?