LoginSignup
0
0

More than 1 year has passed since last update.

Rails link_toで関数を渡す

Posted at

背景

レシピ共有アプリ制作にて以下のような問題がありました

モデル
class User < ApplicationRecord
has_many: recipes
has_one: list
end

class Recipe < ApplicationRecord
belongs_to: user
has_many: ingredients
end

class Ingredient < ApplicationRecord
belongs_to: recipe
end

#これは買い物リストのモデルで、追加したいレシピの材料をリストテーブルに保存します
class List < ApplicationRecord
belongs_to: user
end

買い物リストにレシピの材料を追加するときに、

パラメーターの中にレシピの情報を追加したかったのですが、

親子関係ではないのでルーティングのネストをせずに実現したい。。。

迷った末見つけた方法をここに残します

ルーティング
post '/lists', to: 'lists#create', as: 'create_list'
コントローラー
 def create
    #レシピのidを整数に変換
    num = (params[:format]).to_i
    @recipe = Recipe.find(num)
    #レシピの材料を全て取り出す
    @ingredients = @recipe.ingredients
    list = List.new
    @ingredients.each do |ingredient|
      list = List.new(ingredient_name: ingredient.name, ingredient_quantity: ingredient.quantity, user_id: current_user.id)
      list.save
    end
    flash[:notice] = 'リストを追加しました'
    redirect_to "/users/#{current_user.id}"
  end
ビュー
<%= link_to "追加", create_list_path(x), method: :post %>
<!--xにはレシピの情報が入っています-->

この方法だとエラーが発生したときにエラーハンドリングができていません。

ストロングパラメータもないので良くないですが、とりあえずデータベースに保存するための基盤を作りました。

ポイント

ポイントはlists#createアクションに行くときにrecipeの情報をパラメーターに含めたかったので、

<%= link_to "追加", create_list_path(x), method: :post %>この形を取りました。

"/lists"(x), method: :postとかでできないかとやってみましたが、できなかったので、

post '/lists', to: 'lists#create', as: 'create_list'
この記載でcreate_listというprefixを作りました

初学者が足掻いて試した結果なので、もっといい方法などありましたら教えてください。

この記載でストロングパラメーターをつけるとしたらどうすればいいか現在調べてます。

0
0
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
0