Skip to main content

24 Forum Series Part 3: Nested Attributes and fields_for

Episode 27 · October 9, 2014

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

Forms ActiveRecord


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


No transcripts available. Earn a free month

Discussion