LoginSignup
1
2

More than 5 years have passed since last update.

リソースベースの時のlink_toの使い方

Last updated at Posted at 2016-10-30

リソースベースでルーティングを設定し、link_todestroyを使おうとした時につまづいたので備忘録です。

基本的な使い方

まずは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

こうなっています。

ルーティング名があるアクション

neweditなどです。

<%= link_to "新規作成", new_imate_path %>

ルーティング名に_pathをつけて記述します。

editshowのようにidパラメータを指定するアクションの場合は、
モデルオブジェクトを使って記述します。

<%= link_to "更新", edit_image_path(@image) %>

ルーティング名が無いアクション

create,update,destroyです。
HTTPメソッドをmathodオプションで指定して記述します。

<%= link_to "削除", image_path(@image), :method => :delete %>

オブジェクト名だけで指定

showupdatedestroyなど、idパラメータを指定して呼び出すアクションは、オブジェクトのみで簡略化できます。

<%= link_to "Show", @image %>
<%= link_to "delete", @image, :method => :delete %>

こちら参考にさせていただきました。
http://www.rubylife.jp/rails/template/index8.html

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2