0

In my Rails app, I'm trying to get links of events tagged with specified tags in my events#index view. In order to make them linked with link_to, I got the error below:

undefined method `map' for "fgssgf,sfgdsfg,dsgfsdgf,sgfdsg":String` error
  app/views/events/index.html.slim:17:in `block in _app_views_events_index_html_slim__...'

Here are files related with this issue:

index.html.slim:

table.table.table-bordered
  thead
    tr
      th Title
      th Start date
      th End date
      th Location
      th Tags

  tbody
    - @events.each do |event|
      tr
        td = link_to event.title, event
        td = event.start_date
        td = event.end_date
        td = event.location
        td = event.all_tags.map { |t| link_to t, tag_path(t) }.join(', ') # line 17 here

index method in events_controller.rb:

def index
  if params[:tag]
    @events = Event.tagged_with(params[:tag])
  else
    @events = Event.all
  end
end

all_tags & tagged_with methods in event.rb:

def all_tags
  tags.map(&:name).join(",")
end

def all_tags=(names)
  self.tags = names.split(',').map do |t|
    Tag.where(name: t.strip).first_or_create!
  end
end

def self.tagged_with(name)
  Tag.find_by!(name: name).events
end
ekremkaraca
  • 1,453
  • 2
  • 18
  • 37

2 Answers2

2

In addition to Arup's richtig answer; I've done these changes below:

all_tags from event.rb:

def all_tags
  tags.map(&:name).join(',') # return stays same
end

links part from index.html.slim:

td
  - event.all_tags.split(',').map do |t| # single-line could be done but this one is better
    = link_to t, tag_path(t)
Community
  • 1
  • 1
ekremkaraca
  • 1,453
  • 2
  • 18
  • 37
1

The below method

def all_tags
  tags.map(&:name).join(",") # here you are creating an string.
end

should be

def all_tags
  tags.map(&:name)
end

Your method as I said above creating an string, on which you attempted to call the Array#map method. Which of-course not possible. Thus either you need to change the method, so that it returns collection instead of string. Or, if you don't want to change the method, then split the string back to array, so that you can call #map as below

 event.all_tags.split(",").map { |t| link_to t, tag_path(t) }
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317