On Nov 18, 2:07 pm, Demetrius <[email protected]> wrote:
> Hello! I'm looking for assistance EXTENDING an example from the Agile
> Web Development With Rails book: Composing Data with Aggregation (page
> 324).
>
> I'm trying to map three columns to a single Ruby object. However,
> unlike the example in the Agile Web Development book, the three
> columns I want to map into one object come from THREE DIFFERENT
> models.
>

Composed_of is not normally used (or probably designed to be used) in
this way). The basic idea is that you have some raw attributes and you
turn them into a object, for example you might have attributes on your
model called start and finish and use composed_of to create a magic
attribute called Range whose endpoints are those attributes.

If you want your standard object to have the name from the Grade
object, could you just do

def grade_abbr
  grade.grade_abbr
end

(and when you're happy with this, have a look at delegate)

Fred


> I want to map the following three columns into one object:
> grade.grade_abbr, strand.strand_abbr, standard.number (ex. 5 NS 2.3).
> Also, I only need to read the new object--not edit the original
> columns.
>
> Here are the models and their relationships:
>
> class  Standard
>   belongs_to :strand
>   belongs_to :grade
>
> class  Strand
>   has_many :standards
>
> class  Grade
>   has_many :standards
>
> When I originally setup my Standard table with grade_abbr and
> strand_abbr, it easy to follow the example in the Agile Web
> Development because each column was contained within the Standard
> model. However, I had to move Grade and Strand into their own tables,
> so the Standard table contains grade_id and strand_id--not the actual
> objects themselves.
>
> When I played with the example from the Agile Web Development book, I
> couldn't get :grade.grade_abbr and strand.strand_abbr to work. The
> code below was the best that I could come up with but it shows
> grade_id and strand_id.  Does anyone have a suggestion for how to make
> this work or for a new strategy?
>
> class Standard < ActiveRecord::Base
>   composed_of :full_standard,
>               :mapping =>
>                 [
>                   %w[grade_id   grade_id],
>                   %w[strand_id strand_id]
>                   %w[number number]
>                 ]
>
> class FullStandard < ActiveRecord::Base
>   attr_reader :grade_id, :strand_id, :number
>
>   def initialize(grade_id, strand, number)
>     @grade_id = grade_id
>     @strand_id = strand_id
>     @number = number
>   end
>
>   def to_s
>     [ @grade_id, @strand_id, @number ].compact.join(" ")
>   end
> end

--

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=.


Reply via email to