HABTM relationships in views

Hi everyone.
I'm currently working on a bodybuilding supplement Website which have 3
models :

* Stack :
has_and_belongs_to_many :products
* Product :
has_and_belongs_to_many :stacks
has_and_belongs_to_many :ingredients
* Ingredient :
has_and_belongs_to_many :products

Now what I am trying to do is list all the ingredients for a Stack
(using standard params[:id]). It seems that I cannot pass multiple
product_ids (but one id work fine!) to get the ingredients listing.

Here's a partial code from my controller :

=== START ===

  def stack
    begin
      @stack = Stack.find(params[:id])
      render :template => "public/stack_#{@lang}"
    rescue ActiveRecord::RecordNotFound
      logger.error("Attempt to access invalid stack #{params[:id]}")
      flash[:notice] = "Désolé, cette formule est introuvable."
      redirect_to :action => :index
    end
  end

=== END ===

Any help would be appreciate and I can provide more information if my
request isn't clear enought.

I am using RAILS_GEM_VERSION = '1.2.6'

Thanks

Hugues

@stack.products will give you an array of products then for each
product, product.ingredients will give you an array of ingredients.

Colin

product.ingredients is an array, you could reference
product.ingredients[0].name or you could iterate the array using
product.ingredients.each. Another useful construct is
product.ingredients.map(&:name) which will give you an array of
ingredient names.
In all of this don't forget to watch out for a product with no
ingredients (product.ingredients is nil in this case) which can give
you run-time errors if you have not caught them. The same applies to
stack.products.

I wonder whether it would be useful for you to run through some basic
Ruby tutorials to get a bit more grounding on the basics of Ruby.

Good Luck

Colin

product.ingredients is an array, you could reference

In all of this don't forget to watch out for a product with no
ingredients (product.ingredients is nil in this case)

I'm sure you meant to say that product.ingredients is an empty array

I wonder whether it would be useful for you to run through some basic
Ruby tutorials to get a bit more grounding on the basics of Ruby.

Excellent advice, put very nicely.

Best regards,
Bill

Colin Law wrote: