Created
December 11, 2013 00:02
-
-
Save mcconkiee/7902696 to your computer and use it in GitHub Desktop.
creating a polymorphic relationship and form in rails
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 %> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment