簡體   English   中英

嘗試創建“標簽”時未定義的方法“map”

[英]Undefined method 'map' when trying to create 'tags'

我正在重新使用本指南https://rubyplus.com/articles/4241-Tagging-from-Scratch-in-Rails-5,以允許我將'tastingsnotes'作為'roast.rb'模型上的標簽。

但是,當我試圖在瀏覽器中顯示記錄時,我得到錯誤undefined method 'map' 我很確定這不是我不能以某種方式正確映射標簽。 我可以看到當我嘗試編輯記錄時,我在那里有標簽。

邏輯是我有一個名為'Roasts'的模型我希望用戶能夠添加以逗號分隔的品嘗筆記列表。 因此,我將這些視為標簽。

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

烤肉/ _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

烤肉/ 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

控制台錯誤:

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:

你做到了

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

返回逗號分隔符串如“choco,beer”

現在你確實映射到下面的字符串

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

你可以試試

  def tastingnotes
    notes.pluck(:name)
  end

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM