Combining two controllers into one

@halogenandtoast

I am working on a similar project like the shouter one but this has a AndroidSettingsController for the settings of the Android device and AppleSettingsController.

Now I combined them both into one SettingsController and this is my class which will be same like the ShoutsController.

class SettingsController < ApplicationController

  def new
    @project = Project.find(params[:project_id])
    @settings = class_name.new
    @fields = @settings.fields

  end

  def create

    @project = Project.find(params[:project_id])
    @device_setting = build_setting
    @setting = @project.settings.build(device_setting: @device_setting)
    @setting.save
    flash.notice = "Settings saved."
    redirect_to @project
  end

  def show
    @project = Project.find(params[:project_id])
  end

  private

  def build_setting
    class_name.new(apple_setting_parameters)
  end

  def class_name
    params["content_type"].constantize
  end

  def class_underscore
    params["content_type"].underscore.to_sym
  end
  def apple_setting_parameters
    params.permit!
    params[class_underscore]
  end
end

And also I changed the form for creating a new form like this

<%= form_for [@project,@settings],url:project_settings_path(@project,@settings) do |f| %>
  <% if @settings.errors.any? %>
    <div class="error_pushs">
      <h2><%= pluralize(@settings.errors.count, "error") %> prohibited this setting from being saved:</h2>
      <ul>
      <% @settings.errors.full_push.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>
 
  <%= render "#{@settings.class.to_s.underscore.to_s}s/form",f: f %>
 

 <div class="actions"><%= f.submit "Save Settings" %></div>
<% end %>

And this is how I am creating the relevant fields using _form.html.erb for each AndroidSetting and AppleSetting model.

 <div class="field">
    <%= f.label :password %><br />
    <%= f.text_area :password %>
  </div>
 <div class="field">
  <%= f.label :cert %><br />
  <%= f.file_field :cert %>
</div>

 
 <%= hidden_field_tag :content_type,  @settings.class %>

Let me know if this is the right thing to do?

It’s hard to say what the right thing to do is here. You want to be wary of how your application will change. Currently you have two different types of settings per device (Apple or Android). I wouldn’t say anything seems immediately wrong. You could pull

<%= render "#{@settings.class.to_s.underscore.to_s}s/form",f: f %>

Into a helper method:

<%= render_settings_fields(@settings, form) %>

It will at least clean up the view a little.