mcconkiee
12/11/2013 - 12:02 AM

creating a polymorphic relationship and form in rails

creating a polymorphic relationship and form in rails

# Polymorphic Model
class Attachment < ActiveRecord::Base
  belongs_to :attachable, :polymorphic => true
  mount_uploader :image, ImageUploader
end

# Has Many Model
require 'carrierwave/orm/activerecord'
class Exercise < ActiveRecord::Base
  has_many :images , :as=> :attachable, :dependent => :destroy   ,:class_name => "Attachment"
  accepts_nested_attributes_for :images
  mount_uploader :avatar, AvatarUploader
end

# Controller (Exercise)
# Never trust parameters from the scary internet, only allow the white list through.
    def exercise_params
      params.require(:exercise).permit(
          :title,
          :instruction,
          :avatar,
          :images_attributes =>[:image] #nested attributes
      )
    end
    
#Form
<%= form_for(@exercise,:html => {:multipart=>true}) do |f| %>
    <%= f.fields_for :images,Attachment.new do |i| %>
        <%= i.file_field :image %>
    <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>