2009/4/29 Chris Hanks <[email protected]>

>
> Sorry, no, I'm looking for questions and examples to each belong_to one
> tutorial, and a given tutorial has_many examples and has_many questions.
> What I'm really looking for is a way to refer to questions and examples
> together in certain situations.
>
> I'm wondering if I can do something like this (crazy fantasy code):
>
> class Tutorial < ActiveRecord::Base
>   has_many :questions, :as => :sections
>   has_many :examples, :as => :sections
> end
>
> That way, questions and examples could be represented as different
> sections of a tutorial. Then, when I want to display a table of contents
> for a tutorial, I could write:
>
> <% for section in @sections do %>
>   <%= section.title %>
> <% end %>
>
> And get:
> (an example title)
> (a question title)
> (an example title)
> (an example title)
> (a question title)
> (a question title)
> (an example title)
> ...
>
> In the order they appear. I'd also need a "position" attribute on the
> sections for each tutorial, also, to make sure they appear in the right
> order.
>
> Does that make sense? I think single table inheritance might do this,
> but I'm planning on using examples and questions for a bunch of other
> things, so I don't think it would work that well. I'm thinking about
> defining a whole new "section" model, and using that, but I don't know
> yet.
>
>

You could define a Section model which belongs_to your Tutorial model and
has a position attribute so you can determine the order.

In your Tutorial model
    has_many :sections ,  :order => 'sections.position ASC'

You then set up your Example and Question models so that they have a
polymorphic has_many association with the Section model.

In Section:
    belongs_to :sectionable , :polymorphic => true

In Question or Example:
    has_many :sections , :as => :sectionable

Now you can say:

    @tutorial.sections.each do |section|
      section=section.sectionable
      case section
      when Example
        puts section.some_example_method
      when Question
        puts section.some_question_method
      else
        puts 'what!'
      end
    end


Has the nice benefit that you can recycle your examples and questions in
next year's tutorial if you're lazy  :)

-- 
Daniel Bush

http://blog.web17.com.au
http://github.com/danielbush/sifs/tree/master
http://github.com/danielbush

--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to