First off, apologies about my previous empty post.
Also, apologies for the newbie nature of this post. I am new to rails
and I’m working on a simple relational database to be administered
and accessible to the public through rails. I have a question about
aggregation as outlined in the pragprog “agile web development” book,
around page 258 to 260. My example is nearly identical to the one
used in the book. I have basically followed the example there to the
letter, the only difference is that I want to aggregate fields from a
model called Author rather than Customer, and one of the field names
is different.
My question is simply this, once the Author model refers to the new
Name model, how can I access the new :name attribute of instances of
Author? I tried to do that in a view with the following code:
author[:name] %>
anything. The book shows how to created a new instance of Customer
with the aggregate Name object, but what about instances from a
database record? Shouldn’t they have a :name attribute if they have
all the attributes that it’s composed of?
The code I’ve used for Author and Name models is below. Thanks in
advance for any info on where I’m going wrong.
*** app/models/author.rb ***
class Author < ActiveRecord::Base
has_and_belongs_to_many :books
validates_presence_of :first_name, :last_name
composed_of declaration maps Author attributes to the Name model
object
composed_of :name,
:class_name => Name,
:mapping =>
[ [ :first_name, :first ],
[ :other_name, :other],
[ :last_name, :last]
]
end
*** app/models/name.rb ***
Class defines the Name object, aggregation of attirbutes of Author
object.
class Name
attr_reader :first, :other, :last
def initialize(first, other, last)
@first = first
@other = other
@last = last
end
def to_s
[ @first, @other, @last ].compact.join(" ")
end
end