Sunday 15 April 2012

Best way to define global objects in Ruby on Rails -



Best way to define global objects in Ruby on Rails -

i have app has 2 models category , product

products belong categories.

i have created navbar dropdown requires @category , @product object available across entire app (the navbar shown on every page of application.)

what can't work out best place set these basic definitions without defining them multiple times in every page definition.

i need define following:

@category = category.all @products = @category.products.all

the navbar loop this.

<% @category.each |c| %> <%= c.name %> <% @products.each |p| %> <% link_to product_path(p) %> <%= p.name %> <% end %> <% end %> <% end %>

i bit of rails newbie sure there errors in here help much appreciated!

if need them in every single page of app, can set them in applicationcontroller's before_filter:

class applicationcontroller before_filter :get_categories # ... private def get_categories @categories = category.includes(:products) end end

then, can write in view:

<% @categories.each |category| %> <%= category.name %> <% category.products.each |product| %> <%= link_to p.name, p %> <% end %> <% end %>

i fixed other errors , convention incompatibilities.

ruby-on-rails ruby object model-view-controller

No comments:

Post a Comment