Rails 2.3 nested forms with has_many through checkboxes

I was wondering if anyone knew of a way to combine the new nested
forms in rails 2.3 with a has_many through relationship via
checkboxes. Basically I have a page model, a page_category model and
a category_items join table. Pages have many page categories through
category items. The category_items table is polymorphic so i can use
it for other models who need categories (maybe this is
overcomplicating everything though?).

In a page’s edit form I want to be able to dynamically add new
category fields and then associate the new ones I create and the other
already created page categories to the current page via checkboxes.
Hopefully this makes sense and can actually be done, I’d rather not
have to go to another controller/form just to create and edit page

class Page < ActiveRecord::Base
has_many :category_items, :as => :item, :dependent => :destroy
has_many :page_categories, :through => :category_items, :source
=> :category, :source_type => “PageCategory”, :uniq => true
accepts_nested_attributes_for :page_categories, :allow_destroy =>
true, :reject_if => proc { |attrs| attrs.all? { |k, v| v.blank? } }

class PageCategory < ActiveRecord::Base
has_many :pages, :through => :category_items, :source
=> :item, :source_type => ‘Page’, :uniq => true

class CategoryItem < ActiveRecord::Base
belongs_to :category, :polymorphic => true
belongs_to :item, :polymorphic => true

Page Category partial for my page form (hooks into a jquery script to
dynamically add/remove page category form fields)…

hidden_field_tag “page[page_category_ids][]”, “” %>

    <%- for category in PageCategory.all -%>
  • <%= check_box_tag "page[page_category_ids][]", category.id, @page.page_categories.include?(category), :class => "checkbox" %> <% f.fields_for category do |category_form| %><%= category_form.text_field :title, :style => "width: 200px;", :class => "textfield small formElement" %><% end %>
  • <%- end -%>

Right now, if I try and create or update a page I get the following

ActiveRecord::UnknownAttributeError in Admin/pagesController#update

unknown attribute: page_category
RAILS_ROOT: /Users/rajo/Sites/boilerplate

Application Trace | Framework Trace | Full Trace
active_record/base.rb:2745:in attributes=' /Users/rajo/Sites/boilerplate/vendor/rails/activerecord/lib/ active_record/base.rb:2741:ineach’
active_record/base.rb:2741:in attributes=' /Users/rajo/Sites/boilerplate/vendor/rails/activerecord/lib/ active_record/base.rb:2627:inupdate_attributes’
pages_controller.rb:107:in update' /Users/rajo/Sites/boilerplate/app/controllers/admin/ pages_controller.rb:106:inupdate’


“title”=>“About Us”,

About this site.

“page_category”=>{“title”=>“Default Two”},
Show session dump




Thanks for any help in advance.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs