All Lessons / Forum Series Part 3: Nested Attributes and fields_for

Forum Series Part 3: Nested Attributes and fields_for

#27 ยท October 9, 2014

Your Teacher | Chris Oliver

Hi, I'm Chris. I'm the creator of GoRails, Hatchbox.io and Jumpstart. I spend my time creating tutorials and tools to help Ruby on Rails developers build apps better and faster.

About This Episode

Learn how to use accepts_nested_attributes_for and fields_for to create forms that include associated models in them

Notes

app/controllers/forum_threads_controller.rb

class ForumThreadsController < ApplicationController
  def new
    @forum_thread = ForumThread.new
    @forum_thread.forum_posts.new
  end

  def create
    @forum_thread = current_user.forum_threads.new forum_thread_params
    @forum_thread.forum_posts.first.user_id = current_user.id

    if @forum_thread.save
      redirect_to @forum_thread
    else
      render action: :new
    end
  end

  private

    def forum_thread_params
      params.require(:forum_thread).permit(:subject, forum_posts_attributes: [:body])
    end
end

app/models/forum_thread.rb

class ForumThread < ActiveRecord::Base
  belongs_to :user
  has_many :forum_posts

  accepts_nested_attributes_for :forum_posts

  validates :subject, presence: true
  validates_associated :forum_posts
end

Resources

Discussion

Loading...
logo Created with Sketch.

Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

© 2020 GoRails, LLC. All rights reserved.