Here’s my solution, building off of @dwaynecrooks:
Create a ShoutBuilder model:
class ShoutBuilder
def initialize(user, params)
@user = user
@params = params
end
def build
@user.shouts.build(content: content)
end
private
def content
klass.new(shout_params)
end
def shout_params
@params.require(type).permit(klass::PERMITTED_ATTRIBUTES)
end
def klass
@_klass ||= type.to_s.camelize.constantize
end
def type
@_type ||= @params[:shout_type]
end
end
Add a line to TextShout model:
PERMITTED_ATTRIBUTES = [:body]
And to PhotoShout model:
PERMITTED_ATTRIBUTES = [:image]
Move shout creation back to ShoutsController:
class ShoutsController < ApplicationController
def show
@shout = Shout.find(params[:id])
end
def create
shout = ShoutBuilder.new(current_user, params).build
shout.save || flash.alert = "Could not shout."
redirect_to dashboard_url
end
end
Add the following routes:
%w(photo_shouts text_shouts).each do |type|
resources type, only: [:create],
controller: :shouts,
defaults: { shout_type: type.singularize }
end
Then delete unneeded routes and controllers.
I would love any feedback.
Thanks!