views:

23

answers:

0

I am working on some code today but for some reason I can't seem to get it to work. Some explanation:

I have a system that contains feeds, that consist of feed_entries. There are also some categories with sub_categories. Between the sub_categories and feed_entries there is a has_and_belongs_to_many relationship, which I can not seem to get working.

My code (only the relevant parts):

Models:

class Feed < ActiveRecord::Base
  has_many :feed_entries, :class_name => "FeedEntry", :dependent => :destroy
  accepts_nested_attributes_for :feed_entries
end

class FeedEntry < ActiveRecord::Base
  belongs_to :feed
  has_and_belongs_to_many :sub_categories, :class_name => "SubCategory"

  accepts_nested_attributes_for :sub_categories
end

class Category < ActiveRecord::Base
  has_many :sub_categories, :class_name => "SubCategory", :dependent => :destroy
  has_many :feed_entries, :class_name => "FeedEntry", :through => :sub_categories

  accepts_nested_attributes_for :sub_categories
end

class SubCategory < ActiveRecord::Base
   belongs_to :category
   has_and_belongs_to_many :feed_entries, :class_name => "FeedEntry"
end

Migrations:

class CreateSubCategories < ActiveRecord::Migration
  def self.up
    create_table :sub_categories do |t|
      t.string :name
      t.references :category
      t.timestamps
    end

  create_table :feed_entries_sub_categories, :id => false do |tfc|
    tfc.integer :feed_entry_id
    tfc.integer :sub_category_id
  end
end

  def self.down
    drop_table :sub_categories
    drop_table :feed_entries_sub_categories
  end
end

Views:

<% form_for(@feed) do |feed_form| %>
  <% if @feed.errors.any? %>
    ...
<% feed_form.fields_for :feed_entries do |entry_form| %>
  ...

  <% entry_form.fields_for :sub_categories do |sc_form| %>
    <%= sc_form.collection_select(:sub_categories, :id, @sub_categories, :id, :name, {:include_blank => true, :selected => :sub_category_id }) %>
  <% end %>

<% end %>

  <%= feed_form.submit %>
</div>
<% end %>

This view does not render the sub_categories. I tried a number of things but none of them seems to work. I'm not sure what I am doing wrong.

If I replace:

<% entry_form.fields_for :sub_categories do |sc_form| %>
    <%= sc_form.collection_select(:sub_categories, :id, @sub_categories, :id, :name, {:include_blank => true, :selected => :sub_category_id }) %>
  <% end %>

with:

 <%= select(:sub_categories, @sub_categories.collect{|sc| [sc.name, sc.id]},{:include_blank => true, :selected => :sub_category_id }) %>

it renders the selection_box, but changes are not saved, because in the 'params' variable "sub_categories" is not part of the 'feed'.

I'll be looking for a solution tomorrow, but any thoughts are welcome...

Thanks! Jan