LoginSignup
81
68

More than 5 years have passed since last update.

link_to,button_toでcreate, updateを行う

Posted at

hogeモデルのcreate,updateにformからでなくlink_to、button_toからデータを投げる方法の覚書。

ルーティングのおさらい

  • createはindexと同じhoges_path, method: post
  • updateはhoge_path, method: put

create

= link_to 'Create', hoges_path(hoge: {user_id: current_user.id, body: 'fuga'}), method: :post
= button_to 'Create', hoges_path(hoge: {user_id: current_user.id, body: 'fuga'})

update

= link_to 'Update', hoge_path(@hoge), method: :put, params: { body: 'fuga' }
= button_to 'Update', hoge_path(@hoge), method: :put, params: { body: 'fuga' }

注意点

  • getの時と同じようにパラメーターがURLに付与されてしまうのでパラメーターを隠す目的でpostを指定する場合には使えない。
  • button_toだとhtmlでは<button> タグになるが、buttonタグはIE7以下だとバグがあるらしい。button_toではtype="submit"が自動的に付与されているのであまり気にしなくても平気かもしれないけれど一応注意。
    [参考]button要素で送信・リセット・汎用ボタンを自由に作ろう http://honttoni.blog74.fc2.com/blog-entry-153.html

link_to method: :postでパラメータをURLに含めずに送る方法

結論から言うと、railsのみで対応する方法は見つからず、jQueryに頼る他なかった。
自分は↓のを使わせていただきました。この場を借りて多謝。
http://www.techscore.com/blog/2013/10/11/rails-link_to-で-post-したら-request-too-long-と言われたあなたへ/

疑問点

railsのapi docを見ると、button_toのオプションではparamsを取れることになっていて、以下の説明がついていた。

Hash of parameters to be rendered as hidden fields within the form

しかし、第2引数にparamsを置いてもhidden fieldにはならず、以下のようにbuttonタグ内に置かれてしまう。

= button_to 'Create', hoges_path, params: {body: 'fuga'}, method: :post

   ↓

<button params="{:body=>"fuga"}">Create</button>
<input name="authenticity_token" type="hidden" value="r9zz5Bsp1RSm/qhdNzpDai1cdG4OSm2lcPlqyM2txPE=">

書き方が悪いのか、なんでなのか。。。わかる人がいたら教えてください。

81
68
4

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
81
68