LoginSignup
0
1

More than 3 years have passed since last update.

link_toでカラムに値を代入する

Last updated at Posted at 2020-02-25

link_toで飛ぶと同時にカラムに値を代入する様にするまでの方法をまとめます。
今回は飲食店の投稿サイトを例に使います。

お店の詳細情報ページから、そのお店のレビューを投稿するためにlink_toを用いてshop_idをlink_toに持たせてレビューを投稿できる様にします。

使いたい値をlink_to内で飛ばす

show.html.erb
...

<%= link_to "お店について投稿する", new_post_path(:shop_id => @shop.id) %>

...

お店の詳細ページでレビュー(postsモデル)が持つ:shop_idカラムにお店のidカラムをlink_to内で代入します。こうすることで飛んだ先のpostsのnewページのurlは
localhost:3000/posts/new ?shop_id=1
という形になりparams[:shop_id]で受け取れる様になります。

link_toで飛ばした先のアクションで値を受け取る

posts_controller.rb
 def new
   @post = Post.new
   @post.shop_id = params[:shop_id]
 end

先ほどのurlから値を受け取ります。

form_with内でf.hidden_fieldを使い受け取った値を使う

new.html.erb
 <%= form_with(model: @post) do |f| %>
  ...
  <%= f.hidden_field :shop_id, :value => @post.shop_id %>
  <%= f.submit "投稿する" %>
 <% end %>

f.hidden_fieldを用いてユーザーが入力することなくform_with内でパラメータを引き渡します。
これでlink_toで飛ばしたshop_idをpostsのcreateアクションに引き渡すことができました。

追加: path指定ではなく、コントローラ、アクション指定の場合

follow_index_link
#以下のlink_toではrelationshipsコントローのfollowingアクション内で
#params[:id]でuser.idを受け取ることができます。
<%= link_to "フォロー数", {controller: :relationships, action: :following, 
                         id: user.id} %>
0
1
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
0
1