I’m new in Rails, and I’m building my first application. I’m trying to
make
a FAQ for this application, organized by product (questions about each
product) and category (questions of different categories or topics), and
there is something I can’t figure it out how to do.
I have these tables:
create_table “faqs” do |t|
t.column “question”, :text
t.column “answer”, :text
t.column “product_id”, :integer
t.column “category_id”, :integer
t.column “position”, :integer
end
create_table “products” do |t|
t.column “name”, :string
t.column “description”, :text
end
create_table “categories” do |t|
t.column “name”, :string
t.column “description”, :text
t.column “position”, :integer
end
And these models:
class Product < ActiveRecord::Base
has_many :faqs, :order => “category_id, position”
has_many :categories, :through => :faqs, :select => ‘DISTINCT
categories.’
end
class Category < ActiveRecord::Base
has_many :faqs, :order => “product_id, position”
has_many :products, :through => :faqs, :select => 'DISTINCT products.’
acts_as_list
end
class Faq < ActiveRecord::Base
belongs_to :product
belongs_to :category
acts_as_list :scope => :category
end
And I’d like to do something like this:
— Controler —
class FaqsController < ApplicationController
def show
@categories = Product.find(1).categories
End
end
— View —
<% for category in @categories %>
category.name
<% for faq in @category.faqs %><%= faq.question %>
<%= faq.answer %>
<% end %> <% end %>Is this possible? I’ve been working on it for several hours and I
haven’t
found a solution.
Also I’d like to make a question available to all products by setting
its
product_id to 0. How could I hack into the “has_many :faqs” definition
in
the Product model to search, not only the questions assigned to the
current
product, but also all the questions with product_id == 0. Is there a way
to
do that?
Thanks in advance,
Jesús Dugarte.-