社内SEの独り言

WEBの学びをつらつらと書いていきます

form_with

form_withのmodel指定について

= form_with model: [post, comment], class: 'd-flex mb-0 flex-nowrap justify-content-between', remote: true do |f|
  = f.text_field :body, class: 'form-control input-comment-body', placeholder: 'コメント'
  = f.submit '投稿', class: 'btn btn-primary btn-raised'

コメント投稿の機能を実装する部分。

コメント投稿機能のルーティングは以下の通り。(shallowルーティング)

resources :posts, shallow: true do
    resources :comments
  end

コメント投稿のroutesは、http://localhost:3000/rails/info/routesを見ると

post_comments_path POST /post/:post_id/commentsとなっているため、modelが複数必要となる。

(コメントだけなのでcommentだけで良いのでは?と思ったので調べた。)

modelの指定順番も注意

model [comment, post]とすると以下のようにパスが違うよって言われる。

このルーティング、あったらあったで特定のコメントの先に投稿があるようでちょっと面白いSNSかも・・・