Search code examples
ruby-on-railsruby-on-rails-3ruby-on-rails-3.1ruby-on-rails-3.2

global variable in application controller?


I grap the first country with

 @country = Country.find(1)

Then i my head navigation i make this loop to get the right tags:

%ul.thumbnails
 - @country.tags.find_each(:conditions => "active_house = true") do |a|
     %li.span2
       .thumbnail
         - a.attachments.limit(1).each do |b|
           = image_tag(b.file.url)
         .caption
           %p 
             #{link_to a.url, tag_country_region_houses_path(@country, a.name), :class => 'btn-nav-drop'}

This works fine. But the navigation is global so i created a method in application_controller like this:

helper_method :tags

def tags
      @country = Country.find(1)
      @tags = @country.tags.find_each(:conditions => "active_house = true")
end 

And in the navigation view:

%ul.thumbnails
  - tags do |a|
      %li.span2
       .thumbnail
         - a.attachments.limit(1).each do |b|
           = image_tag(b.file.url)
         .caption
           %p 
             #{link_to a.url, tag_country_houses_path(@country,  a.name), :class => 'btn-nav-drop '}

But i get a error message "no block given (yield)"

Thanks..remco


Solution

  • Well, this is nothing about global variable which should be avoided whenever possible.

    Your problem is in this line

    tag_country_houses_path(@country,  a.name)
    

    There is NO @country exists in View.

    You may wonder why. The reason is helper can't pass instance variables to View, different from controller.

    What your helper all did is to return an array object @tags. The value of this object is available in view, but not instance variable @tags, neither @country.

    The fix? Use something to replace @country. If the association is country has_many tags, you can do it like this:

    tag_country_houses_path(a.country,  a.name)
    

    If not, you can set a method in tag model to get the country.

    And you can even use some includes to make query more efficient but that is another story.

    Also, your helper can be simplified without assigning any variables.

    def tags
      Country.find(1).find_each(:conditions => "active_house = true")
    end