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