HUSTEN
HUSTEN

Reputation: 5197

Why do I get nil error in this case?

Indeed, @community has 4 tags so that it shouldn't return nil error.
However in this case, it returns nil error like this. Why and how can I fix?

ActionView::Template::Error (undefined method `+' for nil:NilClass):

My code

<% @community.tags.each do |tag| %><% tag_strings = tag_strings + tag.name + "," %><% end %>
<%= render 'layouts/twitter', :tag => tag_strings + @community.community_name %>

Upvotes: 0

Views: 40

Answers (3)

benchwarmer
benchwarmer

Reputation: 2774

tag_strings is not initialized when the iteration starts. Perhaps you want to join all tags. If so then try tag_strings = @community.tags.map(&:name).join(", ")

Upvotes: 2

user419017
user419017

Reputation:

..or even more neatly...

class Community < ActiveRecord::Base
  def tags_string
    "#{tags.collect(&:name).join(',')} #{community_name}"
  end
end

= render 'layouts/twitter', tag: @community.tags_string

Upvotes: 0

stef
stef

Reputation: 14268

You can achieve this more neatly like so:

<%= render 'layouts/twitter', :tag => @community.tags.collect(&:name).join(",") + @community.community_name %>

Upvotes: 2

Related Questions