Skip to content

Select Polymorphic Association

scambra edited this page Sep 27, 2012 · 2 revisions

To select records in a polymorphic association, you have to choose first which model you want to select from, so foreign_type column must be added to the form, with :select form_ui, the possible class names as options and update_columns to update the polymorphic association.

class Comment < ActiveRecord::Base  
  belongs_to :commentable, :polymorphic => true  
end  

class Article < ActiveRecord::Base  
  has_many :comments, :as => :commentable
end

class Photo < ActiveRecord::Base  
  has_many :comments, :as => :commentable
end

class CommentsController < ApplicationController
  active_scaffold do |conf|
    conf.columns << :comment_type
    conf.columns[:comment_type].form_ui = :select
    conf.columns[:comment_type].options = {:options => ['Article', 'Photo'], :include_blank => true}
    conf.columns[:comment_type].update_columns = [:comment]
  end
end
Clone this wiki locally