Creating subcategories with acts_as_tree

I’ve been working on my first real RoR project and seemingly everything
is going well except I’m at a loss right now trying to figure out how to
create subcategories.

This is what I have so far:

Database:
Category Table
id
name
parent_id

News Table
id
title
content
category_id

Models:
CATEGORY
acts_as_tree
has_many :news

NEWS
belongs_to category

In my Application Helper I’ve set up the following:

def display_categories(categories)
ret = “


    for category in categories
    if category.parent_id == 0
    ret += “

  • ret += link_to category.name
    ret += find_all_subcategories(category)
    ret += “

  • end
    end
    ret += “

end

def find_all_subcategories(category)
if category.children.size > 0
ret = ‘


    category.children.each { |subcat|
    if subcat.children.size > 0
    ret += ‘

  • ret += link_to h(subcat.name), :action => ‘edit’, :id => subcat
    ret += find_all_subcategories(subcat)
    ret += ‘

  • else
    ret += ‘

  • ret += link_to h(subcat.name), :action => ‘edit’, :id => subcat
    ret += ‘

  • end
    }
    ret += ‘

end
end

In my controller I have set up create for news:
def create
@news = News.new(params[:news])
if @news.save
flash[:notice] = ‘News was successfully created.’
redirect_to :action => ‘list’
else
render :action => ‘new’
end
end

But I’m not sure what to add to this and what to put in my layout to be
able to select what category/subcategory when creating a news item, and
how to create subcategories with-in the parent. If I manually go into
the database and change the id numbers it will display properly ( I can
add <%= display_categories(@categories) %> in my layout ), I’m just
confused as how to create under the correct parent.

Thanks for any help… Very much appreciated.

Sorry, I must have accidently posted this twice.

um … i don’t fully get what your problem is.

instead of listing the categories in a HTML List, put that list in a
select dropdown box, set the name to “category_id”, and the value of
the options to the categories id values.

then when you submit the form and “create” gets called,
params[:news][:category_id] will contain the selected news category.
save the news, and you’re done.

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