リソースベースでルーティングを設定し、link_to
でdestroy
を使おうとした時につまづいたので備忘録です。
基本的な使い方
まずはURLやパスを使った基本的な使い方。
<%= link_to "Serch", 'http://www.google.co.jp/' %>
<%= link_to "Index", "/images/index" %>
ルーティング
config/routes.rb
resources image
確認してみると
$rake routes
images GET /images(.:format) images#index
POST /images(.:format) images#create
new_image GET /images/new(.:format) images#new
edit_image GET /images/:id/edit(.:format) images#edit
image GET /images/:id(.:format) images#show
PATCH /images/:id(.:format) images#update
PUT /images/:id(.:format) images#update
DELETE /images/:id(.:format) images#destroy
こうなっています。
ルーティング名があるアクション
new
やedit
などです。
<%= link_to "新規作成", new_imate_path %>
ルーティング名に_path
をつけて記述します。
edit
やshow
のようにidパラメータを指定するアクションの場合は、
モデルオブジェクトを使って記述します。
<%= link_to "更新", edit_image_path(@image) %>
ルーティング名が無いアクション
create,update,destroyです。
HTTPメソッドをmathod
オプションで指定して記述します。
<%= link_to "削除", image_path(@image), :method => :delete %>
オブジェクト名だけで指定
show
、update
、destroy
など、idパラメータを指定して呼び出すアクションは、オブジェクトのみで簡略化できます。
<%= link_to "Show", @image %>
<%= link_to "delete", @image, :method => :delete %>
こちら参考にさせていただきました。
http://www.rubylife.jp/rails/template/index8.html