简体   繁体   中英

Undefined method 'map' when trying to create 'tags'

I'm repurposing this guide https://rubyplus.com/articles/4241-Tagging-from-Scratch-in-Rails-5 to allow me to have 'tastingsnotes' as a tag on a 'roast.rb' model.

However, I'm getting the error undefined method 'map' when trying to show the record in the browser. I'm fairly sure this is down to me not mapping the tags correctly somehow. I can see when I try to edit the record, I have the tags there.

The logic is that I have a model called 'Roasts' I want the user to be a able to add a comma-separated list of tasting notes. I'm therefore treating these as tags.

roast.rb

class Roast < ApplicationRecord
  has_many :tastings
  has_many :notes, through: :tastings

  def self.tagged_with(name)
    Note.find_by!(name: name).roasts
  end

  def self.note_counts
    Note.select('notes.*, count(tastings.note_id) as count').joins(:tastings).group('tastings.note_id')
  end

  def tastingnotes
    notes.map(&:name).join(', ')
  end

  def tastingnotes=(names)
    self.notes = names.split(',').map do |n|
      Note.where(name: n.strip).first_or_create!
    end
  end
end

note.rb

class Note < ApplicationRecord
  has_many :tastings
  has_many :roasts, through: :tastings
end

tasting.rb

class Tasting < ApplicationRecord
  belongs_to :note
  belongs_to :roast
end

roasts/_form.html.rb

//items not pasted for brevity
      <div class="form-group">
        <%= form.label :tastingnotes, "Notes (separated by commas)", class: 'control-label' %><br  />
        <%= form.text_area :tastingnotes, id: :roast_tastingnotes, class: "form-control" %>
      </div>
//items not pasted for brevity

roasts/show.html.rb

//items not pasted for brevity
<p>
  <strong>Tasting Notes</strong>
  <%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>
</p>
//items not pasted for brevity

Console error:

Completed 500 Internal Server Error in 18ms (ActiveRecord: 1.1ms)



ActionView::Template::Error (undefined method `map' for "chocolate, citrus":String
Did you mean?  tap):
    39:
    40: <p>
    41:   <strong>Tasting Notes</strong>
    42:   <%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>
    43: </p>
    44:
    45:

You did

 def tastingnotes
    notes.map(&:name).join(', ')
  end

which return String of comma seperated like "choco, beer"

Now you did map to a string in below

<%= raw @roast.tastingnotes.map(&:name).map { |t| link_to t, tastingnotes_path(t) }.join(', ') %>

You can try

  def tastingnotes
    notes.pluck(:name)
  end

and

<%= raw @roast.tastingnotes.map { |t| link_to t, tastingnotes_path(t) } %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM