1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

【Rails】スレッドのレス投稿機能

Posted at

プログラミング初心者です。
Ruby on Railsで掲示板のスレッドにレスを紐付けて投稿していく機能を作成しました。
結構苦戦したので、備忘のため貼り付けます。

【スレッド(親、tree)controller】

  def show
    @tree = Tree.find(params[:id])
    @response = Response.new(:tree_id => params[:id]) #ここを投稿用に使う
    @responses = @tree.responses.all
  end

【レス(子、response)controller】

  def create
    @response = current_user.responses.new(response_params)

    if @response.save
      redirect_to tree_url(@response.tree_id), notice: "投稿「#{@response.text}」を登録しました"
    else
      render tree_url(@response.tree_id)
    end
  end

  private

  def response_params
    params.require(:response).permit(:text, :user_id, :tree_id)
  end

【スレッド(親、tree)viewのshow】

= form_with model: @response, url_for: { controller: :responses, action: :create }, local: true do |f|
  .form-group
    = f.label :text, "コメント"
    = f.text_field :text, class: "form-control", id: "response_text"
  = f.hidden_field :tree_id
  = f.submit "投稿", class: "btn btn-primary"

【routes.rb】

  post "/responses", to: "responses#create"
  resources :trees

感想

特にルーティングエラーが多く発生しました。肝となるコードは以下の2点です。

# 入力フォーム
url_for: { controller: :responses, action: :create }
# ルーティング
post "/responses", to: "responses#create"
1
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
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?