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
How To Build A Forum in Rails 4.2
0% Complete
1
Forum Series Part 1: Architecture
16m
2
Forum Series Part 2: Routes
7m
Forum Series Part 3: Nested Attributes and fields_for
9m
4
Forum Series Part 4: div_for
7m
5
Forum Series Part 5: Email Notifications with Rails 4.2, deliver_later, and Previews
20m
6
Forum Series Part 6: Search with Ransack
10m
7
Forum Series Part 7: Time Zones using the local_time Gem
12m