Sure
apps_controller.rb
class Admin::AppsController < AdminController
def index
@apps = App.all
end
def new
@app = App.new
@app.screenshots.build
end
def create
@app = App.new(params[:app])
if @app.save
redirect_to admin_apps_path
else
@app.screenshots.build
render 'new'
end
end
def edit
@app = find_app
end
def update
@app = find_app
if @app.update_attributes(params[:app])
redirect_to admin_apps_path
else
render 'edit'
end
end
def destroy
@app = find_app
@app.destroy
redirect_to admin_apps_path
end
private
def find_app
@app = App.find(params[:id])
end
end
app.rb
class App < ActiveRecord::Base
attr_accessible :name, :website, :description, :ios_url, :android_url, :icon, :screenshots_attributes
has_many :screenshots
has_attached_file :icon
accepts_nested_attributes_for :screenshots, allow_destroy: true
validates :name, presence: true
validates :ios_url, presence: true, unless: :android_url?
validates :android_url, presence: true, unless: :ios_url?
validates :description, presence: true
validates :icon, presence: true
validates :screenshots, presence: true
end
screenshot.rb
class Screenshot < ActiveRecord::Base
belongs_to :app
attr_accessible :image
has_attached_file :image
end
_form.html.erb (rendered for new and edit in apps)
<%= simple_form_for [:admin, @app], html: { multipart: true } do |form| %>
<h1><%= form_title(form) %></h1>
<%= form.input :name %>
<%= form.input :website %>
<%= form.input :ios_url, label: "iOS Download Link" %>
<%= form.input :android_url, label: "Android Download Link" %>
<%= form.input :description %>
<%= form.input :icon %>
<%= form.simple_fields_for :screenshots do |screenshot_fields| %>
<%= label_tag nil, "Screenshots" %>
<%= render 'screenshot_fields', form: screenshot_fields %>
<% end %>
<div class="input">
<%= link_to_add_fields("Add Screenshot", form, :screenshots) %>
</div>
<%= form.button :submit %>
<% end %>
_screenshot_fields.html.erb
<% if form.object.new_record? %>
<%= form.input :image, label: false %>
<% else %>
<%= image_tag form.object.image.url %>
<%= form.hidden_field :_destroy %>
<%= link_to "Delete Screenshot", "#", class: "js-remove-fields remove-fields" %>
<% end %>