On Jun 11, 2010, at 8:02 , Jeremy Evans wrote:
> On Jun 11, 12:40 am, Dave Howell <[email protected]>
> wrote:
>> I was all set to go ahead and 'create an accessor method myself' and then
>> realized I'm really not sure what to make it *on.*
>> Well, on each member of self.ingredients, but the only way I see to do that
>> is (I think), to use :after_load to iterate through each one and add a
>> singleton method for 'percentage' to each. That seems very clunky. Is there
>> a better way?
>
> If you want to create an accessor method just on objects retrieved
> from that association, not really. The better way would be to use
> [:percentage] instead of .percentage.
Hmm. It seems rather un-Ruby-ish.
Recipe.first.ingredients.first.name
Recipe.first.ingredients.first.flavor
Recipe.first.ingredients.first[:percentage]
For the sake of anybody else who might find this thread in the future, I came
up with two alternative solutions.
1) Since adding an accessor to the table between the two tables of a
many_to_many is rather tricky, I changed it to a one_to_many relationship on
the linking table, added a many_to_one relationship from the linking object to
the ingredient object, and defined accessor methods on the linking object to
pull the remaining data through from the ingredient object.
Before:
class Recipe < Sequel::Model
many_to_many :ingredients, :select=>{:ingredients.*,
:recipes_ingredients__percentage}
end
class Ingredient < Sequel::Model
end
After:
class Recipe < Sequel::Model
one_to_many :components, :join_table=>:recipes_ingredients
end
class Component < Sequel::Model
set_dataset :recipes_ingredients
many_to_one :ingredients
def name
self.ingredient.name
end
def flavor
self.ingredient.flavor
end
end
class Ingredient < Sequel::Model
end
Now I can say "Recipe.first.components.first.percentage" but as written, it
does make .name and .flavor read-only, which is OK with me in this situation.
However, this is probably not the solution I'm going to use.
2) Create a view in the database that binds 'name', 'flavor', and 'percentage'
together in one pseudo-table, and create an accompanying rule that allows
updates on the percentage, and then create a simple one_to_many relationship
from the recipe object to an object with the view as the dataset.
--
You received this message because you are subscribed to the Google Groups
"sequel-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/sequel-talk?hl=en.